Search code examples
c++classvirtual

Are Virtual Base classes a workable and or useful feature


I understand that virtual base class mechanism exists to prevent the "Diamond" problem. But I am curious if the situation is not better handled by re-designing the class hierarchy. Take the case below: copied from here

class A { public: void Foo() {} };
class B : public virtual A {};
class C : public virtual A {};
class D : public B, public C {};

The problem I see with the mechanism as it exists now, is you need to be able to predict that someone is going to come along and inherit from both B and C. So does not mean we are better off tagging every inheritance with virtual?


Solution

  • Virtual inheritance of a class A means that

    • A must be initialized in the most derived class, and
    • access of A things becomes somewhat less efficient (because the A sub-object can be shared between several derived class objects, and thus can be at a dynamic offset in each).

    For these reasons virtual inheritance is used with some care.

    One good rule of thumb is to use virtual inheritance for interfaces, and not for implementation classes.