A question on inheritance

Suppose I have a number of similar classes that contain some variables and some functions in common, call the classes B,C and D, and supposed they are all derived from a base class A. If I want to implement a method on them that prints something like "Hello, Im class B", "Hello, I'm class C", etc, then clearly I could achieve this by using a virtual class in A that has no definition and overriding the definition in each of my derived classes. What I want to know is if there is a way to exploit the fact that the functions are essentially performing the same task ie printing the same message, except for the fact that they are each printing their own class name, to save me from having to write the method separately in each derived class. ie to save me from doing this: void B::message() {cout<<"Hello, Im B";}, void C::message() {cout<< "Hello, I'm C";}, etc, which means writing the same code over and over.

I hope this question makes sense to someone. I'm quite new to C++ so would appreciate any help.

thanks,


koenigs
You can implement the common part in the base class
eg:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class A
{
    public:
        virtual void greet()
        {
            cout << "Hello I'm ";
        }
};

class B: public A
{
    public:
        void greet()
        {
            A::greet();
            cout << "B";
        }
};
-A different function (not the virtual one) to have the common part may be a better choice-
You will have to write the function seperately for each class. This is due to the fact that they're all seperate functions.

You can, however, consolidate common code into another function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class A
{
public:
  virtual void Message() = 0;

protected:
  virtual void PrintMessage(const char* classname)
  {
    cout << "Hello, I'm " << classname;
  }
};

//-----------
class B : public A
{
  virtual void Message() { PrintMessage("B"); }  // etc
};


EDIT: doh, Bazzy is too quick
Last edited on
Thanks guys for the speedy response! I hadn't thought of doing it that way.

koenigs
Topic archived. No new replies allowed.