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

  • For example, we consider four classes A, B, C, and D.
  • If 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 C inherited or it is class D that B inherited as a result, compiler throws an error.
  • We declare that B and C inherit A virtually, to remove this ambiguity.
  • It ensures that an object of type D will contain only set of member variables from A.

Sample Code

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

Categorized in: