Search code examples
c++multiple-inheritance

How can I avoid the Diamond of Death when using multiple inheritance?


http://en.wikipedia.org/wiki/Diamond_problem

I know what it means, but what steps can I take to avoid it?


Solution

  • A practical example:

    class A {};
    class B : public A {};
    class C : public A {};
    class D : public B, public C {};
    

    Notice how class D inherits from both B & C. But both B & C inherit from A. That will result in 2 copies of the class A being included in the vtable.

    To solve this, we need virtual inheritance. It's class A that needs to be virtually inherited. So, this will fix the issue:

    class A {};
    class B : virtual public A {};
    class C : virtual public A {};
    class D : public B, public C {};