Virtual Base Class in Multi-path inheritance in C++

The type of inheritance in which already 2 derived classes are combined as a base for another derived class is called multi-path inheritance.

 

In figure above, we see that the grandparent is the initial base class [or sometimes called as ancestor base class].

Parent1 and parent2 are derived from grandparents.

Due to this, property of grandparent is inherited in 2 classes parent1 and parent2/

Again a childclass is formed, combining parent1 and parent2 as a base class.

Due to this, finally derived class “child”, there are 2 copies of properties of grandparent via parent1 and parent2.[THIS IS THE PROBLEM]

SOLUTION

In order to avoid this, multiple copies of grandparent in child class, we use the concept of virtual base class

WHAT WHAT-:VIRTUAL BASE CLASS????????

i.e ancestor base class is made virtual while deriving 2 classes parent1 and parent2.

After this, we can be sure that only a single copy of grandparent is inherited in a finally derived class child.

How to write the program?

hmm

we first remember that grandparent figure(above).

so our grandparent=Base

parent1=derived1

parent2=derived2

child=derived

from base, we will derive derived1 and derived2.

and from derived1 and derived2,

we will make “derived” class.

 

This multi-path inheritance is also called as virtual inheritance.

Output-:

enter the value of a base class 5
enter the value to x of a derived class 6
enter the value to y of a base class 7
enter the value to z of a derived class 8
the total sum is=26

practice this program by writing in copy and then in your own codeblocks.

dedicate time on writing code in codeblocks. it is better if you can write without looking at the code.

Leave a Comment

Your email address will not be published. Required fields are marked *

Do NOT follow this link or you will be banned from the site! Scroll to Top