Diamond Shaped Inheritance


Let's now discuss a classic C++ inheritance issue of diamond shaped inheritance

Consider this example:
class myClassBaseCommon {};
class myClassBase1 : public myClassBaseCommon { };
class myClassBase2 : public myClassBaseCommon { };
class myClassDerived: public myClassBase1, public myClassBase2 { };

In this case, the object of myClassDerived will have two copies of myClassBaseCommon. Most of the time this behaviour is not desirable. To solve this problem, virtual base class is used. After using the virtual base class, the inheritance code will become -


class myClassBaseCommon {};
class myClassBase1 : virtual public myClassBaseCommon { };
class myClassBase2 : virtual public myClassBaseCommon { };
class myClassDerived: public myClassBase1, public myClassBase2 { };

After making the myClassBaseCommon virtual base class, there will be only one copy of this in the object of myClassDerived. Object model will be implemented similarly to one which is described in the previous page. The offset of this in the object of myClassDerived will be obtained from the vtable. The C structure for myClassDerived will look like

struct myClassDerived
{
    struct myClassBase base1;
    struct myClassBase2 base2;
    // members defined in myClassDerived will come here.
    struct myClassBaseCommon common;
};

In this struct, the base1 and base2 do not contain the object of myClassBaseCommon. As the base1 and base2 have virtual bases, they have vtable pointers. Their vtable pointers have the offset to locate the object of myClassBaseCommon from itself. These offset point to the one which is defined as the last member (common). This is the responsibility of the constructor of myClassDerived to override the vtable of its base classes and set the proper offset. As we have seen previously the derived class always overrides the vtable of the base classes. Note that this constructor (which does the overriding of vtable) is not written by programmer, but generated by compiler and implicitly called for each object creation of this type.



Here is diagram to to describe this:

 

up

Want to learn (C/C++ internals) directly from the author using video call? Learn more

Do you collaborate using whiteboard? Please try Lekh Board - An Intelligent Collaborate Whiteboard App