1

I was experimenting with inheritance and I came across a particular behaviour. First, look at the code:

class animal
{
public:
    int ID;
    animal(int id) : ID(id)
    {
        cout<<"I am an animal and I am not a terrorist. Here is my ID: "
        <<ID<<endl;
    }
};

class lion : virtual public animal
{
public:
    lion(int id) : animal(id)
    {
        cout<<"I am a lion and I am not a terrorist. Here is my ID: "
        <<ID<<endl;
    }
};

class tiger : virtual public animal
{
public:
    tiger(int id) : animal(id)
    {
        cout<<"I am a tiger and I am not a terrorist. Here is my ID: "
        <<ID<<endl;
    }
};

class liger : public lion, public tiger
{
public:
    liger(int id) : lion(id), tiger(id), animal(id)
    {
        cout<<"I am a liger and I am not a terrorist. Here is my ID: "
        <<ID<<endl;
    }
};

When the constructor of liger was liger(int id) : lion(id), tiger(id), animal(id)... and I created a object like liger l(444) then I got the following expected output:

I am an animal and I am not a terrorist. Here is my ID: 444
I am a lion and I am not a terrorist. Here is my ID: 444
I am a tiger and I am not a terrorist. Here is my ID: 444
I am a liger and I am not a terrorist. Here is my ID: 444

Then I changed it to to liger(int id) : lion(55), tiger(55), animal(id) but it too gave the same output. Now, my question is, if the arguments to the lion and tiger constructors are neglected, then what is their purpose?

Shravan
  • 2,809
  • 2
  • 18
  • 39
  • 2
    As you use virtual inheritance, the constructor of base class is only called once is the most derived class. – Jarod42 Oct 03 '14 at 12:04
  • 1
    [**See this question**](http://stackoverflow.com/questions/6461784/understanding-virtual-base-classes-and-constructor-calls). Then, 1. how many places in your code do you see `ID` being **set** ? 2. How many places in your *output* do you see that function being invoked ? 3. Why do you think that is? (ans: research when/how virtual base class constructors are fired in a hierarchy like yours. – WhozCraig Oct 03 '14 at 12:09

2 Answers2

0

In virtual inheritance, the constructor of the virtual base is called by the constructor of most derived class, that's the constructor of liger in your case. The calls to animal(id) from lion and tiger constructors are ignored in this case. That's by design.

The reason for this is that you still want to call animal(id) when tiger or lion is the most derived class.

jrok
  • 54,456
  • 9
  • 109
  • 141
0

Only the most derived class actually initializes the virtual baseclass. In other words, the initialization of animal performed by tiger and lion is ignored if (!) they are not the most derived class.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55