Login
Your Email
Pasword
Home
Write
Trending
History
Liked
Dashboard

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

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

Do you have similar website/ Product?
Show in this page just for only $2 (for a month)
Create an Ad
0/60
0/180
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.
CONTINUE READING
Concept of Virtual base class
involved in Multilevel
Multiple
Hierarchical inheritance
Virtual Base Class in C++.
Kinnari
Tech writer at NewsandStory