Virtual inheritance is used to solve the DDD (Dreadful Diamond in Derivation) problem.
Take a look at the following example where you have two classes that inherit from the same base class:
class Base { public: virtual void Ambig(); };
class C : public Base { public: //... }; class D : public Base { public: //... };
Now you want to create a new class that inherits from both the C and D classes (which both inherited the Base :: Ambig () function):
class Wrong : public C, public D { public: ... };
As long as you define the βInvalidβ class above, you actually created DDD (Diamond Derivation Problem) because you cannot call:
Wrong wrong; wrong.Ambig();
This is an ambiguous function because it is defined twice:
Wrong::C::Base::Ambig()
and
Wrong::D::Base::Ambig()
To prevent such a problem, you should use virtual inheritance, which, as you know, will refer to the correct Ambig() function.
So - define:
class C : public virtual Base class D : public virtual Base class Right : public C, public D
ogee Jan 07 '09 at 11:40 2009-01-07 11:40
source share