Search code examples
c++multiple-inheritancevirtual-inheritancediamond-problem

Virtual classes in diamond inheritance with multiple classes in between base class and most derived class


Okay so in the classic diamond inheritance example you have a base class, two classes that inherit from that base class and then another class that inherits from those two, making a nice symmetrical diamond. In that case the two classes inherit virtually from the base class to avoid having two copies of the base class in the most derived class.

But what if there are multiple levels of inheritance in between the base class and the most derived class, as seen in the example diagram below. Do all the classes (B, C, D) need to inherit virtually from their direct base classes or just the ones that are inherit directly (B, C) from the base class? Assuming there are no other classes besides the ones in the diagram.

enter image description here


Solution

  • One does not need to declare C as virtual, since what virtual does is ensure that the class declared as such is contained exactly once, and C is only inherited from once. Basically, the only inheritances that need to be virtual are

    class B : public virtual A { ... };
    class C : public virtual A { ... };
    

    Source: https://en.cppreference.com/w/cpp/language/derived_class