Virtual inheritance

What is the meaning of "virtual" inheritance?

I saw the following code and did not understand the meaning of the virtual in the following context:

 class A {}; class B : public virtual A; 
+43
c ++ inheritance virtual
Jan 07 '09 at 11:20
source share
1 answer

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 
+37
Jan 07 '09 at 11:40
source share
β€” -



All Articles