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;
c++inheritancevirtual
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;
Best Solution
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:
Now, you want to create a new class that inherits both from C and D classes (which both have inherited the Base::Ambig() function):
While you define the "Wrong" class above, you actually created the DDD (Diamond Derivation problem), because you can't call:
This is an ambiguous function because it's defined twice:
And:
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: