- Virtual inheritance
: "For inheritance of virtual functions, see
virtual function ."In the
C++ programming language, virtual inheritance is a kind of inheritance that solves some of the problems caused bymultiple inheritance (particularly the "diamond problem ") by clarifying ambiguity over which ancestor class members to use. It is used when inheritance is representing restrictions of a set rather than composition of parts. A multiply-inherited base class is denoted as virtual with thevirtual
keyword.The problem
Consider the following class hierarchy.But how does
bat
eat()
? As declared above, a call tobat.eat()
is ambiguous. One would have to call eitherbat.WingedAnimal::Animal::eat()
orbat.Mammal::Animal::eat()
.This situation is sometimes referred to as diamond inheritance because the inheritance diagram is in the shape of a diamond. Virtual inheritance can help to solve this problem.
Class representation
Before going further it is helpful to consider how classes are represented in C++. In particular, inheritance is simply a matter of putting parent and child class one after the other in memory. Thus Bat is really (Animal,Mammal,Animal,WingedAnimal,Bat) which makes Animal duplicated, causing the ambiguity.
olution
We can redeclare our classes as follows:Now the
Animal
portion ofBat::WingedAnimal
is the "same"Animal
as the one used byBat::Mammal
, which is to say that aBat
has only oneAnimal
in its representation and so a call toBat::eat()
is unambiguous.This is implemented by providing
Mammal
andWingedAnimal
with avtable pointer since, e.g., the memory offset between the beginning of aMammal
and of itsAnimal
part is unknown until runtime. Thus Bat becomes (vtable*,Mammal,vtable*,WingedAnimal,Bat,Animal). Two vtable pointers per object, so the object size increased by two pointers, but now there is only one Animal and no ambiguity. There are two vtables pointers: one per inheritance hierarchy that virtually inherits Animal: One for Mammal and one for WingedAnimal. All objects of type Bat will have the same vtable *'s, but each Bat object will contain its own unique Animal object. If another class inherits Mammal, such as Squirrel, then the vtable* in the Mammal object in a Squirrel will be different from the vtable* in the Mammal object in a Bat, although they can still be essentially the same in the special case that the squirrel part of the object has the same size as the Bat part, because then the distance from the Mammal to the Animal part is the same. The vtables are not really the same, but all essential information in them (the distance) is.ee also
*
Object association
Wikimedia Foundation. 2010.