Virtual Base Classes
A situation may arise where all the three kinds of inheritance, namely, multilevel, multiple and hierarchical inheritance are involved. This is illustrated in the figure below; the child has two direct base classes 'parent1' and 'parent2' which themselves have a common base class 'grandparent'. The 'child' inherits the traits of grandparent class via two separate paths. It can also inherit directly, as shown by the dotted lines. The grandparent class is sometimes referred to as indirect base class.
Such inheritance by the child class may create some problems. All the public and protected members of the grandparent class are inherited into the child class twice; first via parent1 class and then again via parent2 class. This means that the child class would have duplicate set of members inherited from grandparent, which introduces ambiguity and should be avoided.
The duplication of inherited members 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.
When a class is made virtual base class, C++ takes necessary care to see that only one copy of that class is inherited, regardless of how many inheritance paths exist between the virtual base class and a derived class.
Example:
Consider a student result processing system.
Comments - No Responses to “Virtual Base Classes”
Sorry but comments are closed at this time.