C++ Virtual Base Class

Take a situation where all the three types of inheritance, multiple, multilevel and hierarchical inheritance
are used together. This situation is illustrated in the below image.

What is Virtual Base Class in C++?

The child has two base classes parent1 and parent2 and these two have a common base class grandparent. All the public and protected members of grandparent are inherited into child twice, first from parent1 and again from parent2. This means that child have duplicate sets of members inherited from grandparent. It
causes ambiguity in the program.

 

This kind of problem can be resolved by making the common base class as a virtual base class. It can be done in the following way:

If a class is made a virtual base class, only one copy of that class is inherited in derived class. Remember one thing that the keyword virtual and public may be used in either order.

Below I have written a program that implements the concept of the virtual base class.

What is Virtual Base Class in C++?

 

In the above example student class is an abstract class, as it is not used to create an object. It is used only for deriving other classes.

If you liked this article then don’t forget to comment and share.

Leave a Comment

Your email address will not be published.