virtual inheritance
Virtual inheritance is used to solve the DDD problem (Dreadful Diamond on Derivation).
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 both from C and D classes (which both have inherited the Base::Ambig() function):
class Wrong : public C, public D
{
public:
...
};
While you define the "Wrong" class above, you actually created the DDD (Diamond Derivation problem), because you can't call:
Wrong wrong;
wrong.Ambig();
This is an ambiguous function because it's defined twice:
Wrong::C::Base::Ambig()
And:
Wrong::D::Base::Ambig()
In order to prevent this kind of problem, you should use the virtual inheritance, which will know to refer to the right Ambig()
function.
So - define:
class C : public virtual Base
class D : public virtual Base
class Right : public C, public D
Gal Goldman
Education: M.Sc. in Mathematics B.Sc. in Mathematics & Computer Science Occupation: Current: - CPU Product Development Team Leader | Program Manager at Intel Corporation Past: - Software Project leader at Intel Corporation - Software engineer at Elbit Systems LTD. Experience: Languages: C++/Qt/C#/.NET/C/ADA/Perl Platforms: UNIX/Linux/Windows
Updated on August 31, 2020Comments
-
Gal Goldman over 3 years
What is the meaning of "virtual" inheritance?
I saw the following code, and didn't understand the meaning of the keyword
virtual
in the following context:class A {}; class B : public virtual A;
-
Thomas Eding over 11 years
Wrong
could very well beCorrect
. It depends on the situation. Normal MI and virtual MI both have their places, even in the presense of (not-dreadful) diamond patterns that arise. Just remember that there is no size that fits all. -
Kevin over 9 yearsI think you're drawing attention to the wrong thing - with your "Wrong" and "Right" classes. They're identical for a reason - they're not the problem. While you correctly have the virtual inheritance for the parents C and D, you basically gloss over it - C and D were the ones that were "wrong" and need to be fixed, not the class deriving from both of them.
-
Scott Hutchinson over 5 yearsThis could use a more explicit conclusion. What does it mean to say "virtual inheritance, which will know to refer to the right Ambig() function"? How does it know? It's not obvious to me how this solves the problem.
-
Scott Hutchinson over 5 yearsThis is much clearer for me: stackoverflow.com/a/21607/5652483