Virtual inheritance is used in C++. It is mainly useful in Multiple inheritance. It is a technique in which we can create only one copy of the base class object though it is present in more than one classes of the hierarchy.
When you have a class (A) which inherits from 2 parents (B and C), both of which share a parent (D). If you don’t use virtual inheritance in this case, you will get two copies of D in A: one from B and one from C. To fix this, you need to change the inheritance of classes C and B to be virtual.
```
#include <iostream>
using namespace std;
class A {
public:
A() { cout << "A" << endl; }
};
class B : virtual public A {
public:
B() { cout << "B" << endl; }
};
class C : virtual public A {
public:
C() { cout << "C" << endl; }
};
class D : public B, C {
public:
D() { cout << "D" << endl; }
};
int main() {
D d;
return 0;
}
```