Virtual Base Class in C++
What is Virtual Base Class in C++?
Here, in this section we will discuss about virtual base class in C++. The necessity for the virtual base class is a problem that is faced due to multiple inheritances, in a way we are preventing multiple instances of same function caused due to multiple inheritance. If you look at the code below you will understand the reason why?
Why we need virtual base Classes?
The below program will give error
#include<iostream>
using namespace std;
class GrandParent
{
public:
void print()
{
cout<<"Hello" << endl;
}
};
class Father : public GrandParent
{
//print function inherited from GrandParent
};
class Mother : public GrandParent
{
//print function inherited from GrandParent
};
//multiple inheritance
class Child : public Father,public Mother
{
//print function inherited two times from Father & Mother both
//creating error and ambiguity.
};
int main()
{
Child c;
c.print(); // will generate error here
//print function is inherited two times from Grandparent via Father and mother both
//This causes ambiguity for the compiler
return 0;
}
Output
main.cpp: In function ‘int main()’: main.cpp:34:7: error: request for member ‘print’ is ambiguous c.print()
Why the error is there?
The error is caused as
- Both mother and father classes inherit print function from GrandFather class.
- Child class inherits the print function twice from both mother and father
- This creates two instances of same function in child class which causes ambiguity in compiler on which function to call and is disallowed as an error.
How to solve the below issue?
Check the below example to understand, all we will be changing is adding keyword virtual before classes Father and mother
#include<iostream>
using namespace std;
class GrandParent
{
public:
void print()
{
cout<<"Hello" << endl;
}
};
class Father : virtual public GrandParent
{
//print function inherited from GrandParent
};
class Mother : virtual public GrandParent
{
//print function inherited from GrandParent
};
//multiple inheritance
class Child : public Father,public Mother
{
//print function only inherited once as both mother and father
//have virtual keywords before them
};
int main()
{
Child c;
c.print();
//No Ambiguity now
return 0;
}
Output
Hello
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment