In many tutorials describing the usage of virtual base classes (usually used to solve the diamond problem), they often have a code similar to the design of this structure:
class Animal
{
public:
Animal()
{
cout << "Creating Animal\n";
}
};
///////////////////////////
class FourLegs : virtual public Animal
{
public:
FourLegs()
{
cout << "Creating FourLegs\n";
}
};
///////////////////////////
class Mammal : virtual public Animal
{
public:
Mammal()
{
cout << "Creating Mammal\n";
}
};
///////////////////////////
class Fox : public FourLegs, public Mammal
{
public:
Fox()
{
cout << "Creating Fox\n";
}
};
When I create an instance of Fox, I get the expected output, only one Animal created:
Creating Animal
Creating FourLegs
Creating Mammal
Creating Fox
As you can see, I have the two tier-2 classes inherit virtually. Now, if only one tier-2 class is inherited virtually, and the other is inherited just publicly, interesting outputs can occur. For example, if if FourLegs is inherited public and Mammal is inherited virtual public, this is the output:
Creating Animal
Creating Animal
Creating FourLegs
Creating Mammal
Creating Fox
This is strange and brings up the question: What is the complete process of creating a class that involves virtual inheritance somewhere in the inheritance tree?
On the other hand, if I FourLegs if inherited virtual public, and Mammal is inherited public, then the output is as just normal (as if nothing was inherited virtual public):
Creating Animal
Creating FourLegs
Creating Animal
Creating Mammal
Creating Fox