Search code examples
c++inheritancevirtualvirtual-inheritance

Does "virtual base class in the case of multilevel inheritance" have significance


Consider the following sample codes which shows multilevel inheritance:

Case1 : Here the class derived1 is derived from the class base through virtual inheritance and the class derived2 is derived from the class derived1 directly.

class base
{

};

class derived1 : virtual public base
{

};

class derived2 : public derived1
{

};

Case2 : Same as Case1 except that no virtual inheritance is involved

class base
{

};

class derived1 : public base // no virtual inheritance
{

};

class derived2 : public derived1
{

};

Suppose i create an object of the class derived2 in both cases.

  1. How does Case1 and Case2 differ with respect to the containment of sub-objects with in the object of derived2?

  2. Does Case1 have significance over Case2 ?

PS: I am clear with the importance of a virtual base class during multiple inheritance.


Solution

  • Without multiple instances of a base class in an inheritance hierarchy there are (at least) two other issue to consider with virtual base classes.

    First, a virtual base class is always initialized by the most derived class under construction and before non-virtual base classes. This is most obvious when intermediate classes pass parameters to the virtual base class constructor in their member initialization lists. These initializers will be ignored. It can also make a difference to the order of construction of base classes.

    Second, it is not possible to perform a static_cast from a virtual base class to a class that inherits from it.