Virtual base class in C++



In this tutorial, we will be discussing a program to understand virtual base class in C++.

Virtual classes are primarily used during multiple inheritance. To avoid, multiple instances of the same class being taken to the same class which later causes ambiguity, virtual classes are used.

Example

 Live Demo

#include <iostream>
using namespace std;
class A {
   public:
   int a;
   A(){
      a = 10;
   }
};
class B : public virtual A {
};
class C : public virtual A {
};
class D : public B, public C {
};
int main(){
   //creating class D object
   D object;
   cout << "a = " << object.a << endl;
   return 0;
}

Output

a = 10

Advertisements