Consider a situation where all three kinds of inheritance, namely, multilevel, multiple, hierarchical inheritance, are involved. This illustrated in fig a. the child has two direct base classes, “parent1” & “parent2” which themselves have a common base class “grandparent”. The child inherits the traits of “grandparent” via two separate path . It can also inherit directly as shown by broken line. The “grandparent” sometimes referred to as indirect base class.
Inheritance by the “child” as shown in fig a might pose some problems. All the public & protected members of “grandparent” is inherited into “child” twice, first via “parent1” & again via “parent 2”. This means, “child” would have duplicate sets of the members inherited from “grandparent. This introduces ambiguity & should be avoided. The duplication of inherited members in child class due to these multiple paths can be avoided by making the common base class as virtual base class while declaring the direct or intermediate base classes as shown above.
class Grandparent
{
};
class Parent1: public virtual Grandparent
{
};
class Parent2: public virtual Grandparent
{
};
class Child: public Parent1,public Parent2
{
};