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;
Virtual inheritance is a C++ technique that ensures only one copy of a base class's member variables are inherited by grandchild derived classes.
Virtual inheritance is used when we are dealing with multiple inheritance but want to prevent multiple instances of same class appearing in inheritance hierarchy. From above example we can see that “A” is inherited two times in D means an object of class “D” will contain two attributes of “a” (D::C::a and D::B::a).
Right Answer is: It is a technique to ensure that a private member of a base class can be accessed.
Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that use multiple inheritances. When a base class is specified as a virtual base, it can act as an indirect base more than once without duplication of its data members.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With