class Animal
{
public:
virtual void eat();
};
class Mammal : public Animal
{
public:
virtual Color getHairColor();
};
class WingedAnimal : public Animal
{
public:
virtual void flap();
};
// A bat is a winged mammal
class Bat : public Mammal, public WingedAnimal {};
...
Bat bat;
But how does bat eat()? As declared above, a call to bat.eat() is ambiguous. One would have to call either bat.WingedAnimal::Animal::eat() or bat.Mammal::Animal::eat(). The problem is that semantics of conventional multiple inheritance do not model reality. In a sense, an Animal is only an Animal once; a Bat is a Mammal and a WingedAnimal, but the Animalness of a Bat's Mammalness is the same Animalness as that of its WingedAnimalness.
This situation is sometimes referred to as diamond inheritance and is a problem that virtual inheritance works, in part, to solve.
SolutionWe can redeclare our classes as follows:
// Two classes virtually inheriting Animal:
class Mammal : public virtual Animal
{
public:
virtual Color getHairColor();
};
class WingedAnimal : public virtual Animal
{
public:
virtual void flap();
};
// A bat is still a winged mammal
class Bat : public Mammal, public WingedAnimal {};
Now the Animal portion of Bat::WingedAnimal is the same Animal as the one used by Bat::Mammal, which is to say that a Bat has only one Animal in its representation and so a call to Bat::eat() is unambiguous.
This is implemented by providing Mammal and WingedAnimal with a vtable pointer since, e.g., the memory offset between the beginning of a Mammal and of its Animal 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.