• Follow Us

Virtual Base Class in C++

Virtual Base Class in C++ Program is used in virtual inheritance in such a way as to prevent multiple instances of this class appearing in the inheritance hierarchy when using multiple inheritances.

What is the need for a virtual base class?

Virtual base classes are used in virtual inheritance in such a way as to prevent multiple instances of this class appearing in the inheritance hierarchy when using multiple inheritances.

Let’s consider the situation when we have one class A. This class A is inherited by two other classes B and C. Both of these classes are inherited in another in the new class D, as shown in the figure below.

Virtual Base Class in C++

#include <iostream> 

using namespace std; 

class A { 

public: 

void show() 



cout << "I am from A  Class\n"; 



}; 

class B : public A { 

}; 

class C : public A { 

}; 

class D : public B, public C { 

}; 

int main() 



D object; 

object.show(); 

Learn more about inheritance: C++ Inheritance Programs

Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping cart