views:

285

answers:

4

What is the meaning of "virtual" inheritance? I saw the following code, and I don't understand what is the meaning of the word "virtual" in the following context:

class A {};
class B : public virtual A;

Thanks!

+6  A: 

Have a read of this (it's been asked before).

OJ
+1  A: 

Virtual inherutance 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 ambiguous function because it 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

Ohad
A: 

Read this, if you want learn about object layout.

http://www.cse.wustl.edu/~mdeters/seminar/fall2005/mi.html

chappar
A: 

Isn't it as simple as "virtualness is inherited"? I.e., if you inherit a class with a virtual function - the function will still be virtual in it's subclass irrespective of the subclass definition?

Henrik Hartz