Enter your email id to get regular update free
Login
Your Email
Pasword

Explain the Concept of Virtual Base Class in C++?

Here we understand What is Virtual base class in C++ language in detailed.

Explain the Concept of Virtual Base Class in C++?
Here we understand the Concept in detailed as follows-
Consider a situation where all the three kind of inheritance, namely, multilevel, multiple and hierarchical inheritance are involved.
For example, class "child" has two direct base classes "parent1" and "parent2" which themselves have a common base class "grandparent." The "child" inherits "grandparent" via two separate paths.
All public and protected members of "grandparent" are inherited into "child" twice, first via "parent1" and second via "parent2". This means "child" would have duplicate sets of the members inherited from "grandparent".
This 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 as shown below.
class grandparent
{
} ;
class parent1 : virtual public grandparent
{
} ;
class parent2 : virtual public grandparent
{
} ;
class child : public parent1, public parent2
{
} ;
When the class is made a 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.
Concept of Virtual base class
involved in Multilevel
Multiple
Hierarchical inheritance
Virtual Base Class in C++.
Kinnari
Tech writer at NewsandStory
Total 307 views