Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual inheritance [duplicate]

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; 
like image 528
Gal Goldman Avatar asked Jan 07 '09 11:01

Gal Goldman


People also ask

What is virtual multiple inheritance?

Virtual inheritance is a C++ technique that ensures only one copy of a base class's member variables are inherited by grandchild derived classes.

When you should use virtual inheritance?

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).

Which of the following statement is correct about virtual inheritance?

Right Answer is: It is a technique to ensure that a private member of a base class can be accessed.

Why virtual classes are important in the case of multiple inheritance?

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.


1 Answers

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 
like image 148
ogee Avatar answered Oct 12 '22 11:10

ogee