In this C++ tutorial, you will learn what Virtual Inheritance is, how virtual inheritance works between classes, with examples.

C++ Virtual Inheritance

In C++, Virtual Inheritance is used to remove the ambiguity of base class, when a derived class inherits the same base class via other classes during multiple inheritance.

Quick Example Scenario

Consider that we have four classes: A, B, C and D.

B and C inherit A.

D inherits B and C.

CPP Virtual Inheritance

Now, when an object of type D tries to access members of A, ambiguity arises as to which class it should resolve. If it is class D that B inherited or is it class D that C inherited. As a result, compiler throws error.

To remove this ambiguity, we declare that B and C inherit A virtually. This ensures that an object of type D will contain only set of member variables from A.

ADVERTISEMENT

Example

We shall implement the above scenario with classes B and C inserting A virtually.

C++ Program

#include <iostream>
using namespace std;

class A {
public:
    int x = 2;
};

class B: public virtual A {
};

class C: public virtual A {
};

class D: public B, public C {
};

int main() {
    D d = D();
    cout << "x : " << d.x << endl;
}

Output

x : 2
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned what Virtual Inheritance is, and how to remove the ambiguity of base class during multiple inheritance using virtual inheritance, with the help of examples.