Before we begin coding let me explain the meaning of the given question Virtual base class. To have proper understanding lets consider you have four classes:

  1. Class A
  2. Class B
  3. Class C and
  4. Class D

The task is to Virtualize base class which is class A in our program.

Virtual Base Class

Let’s write the codes


#include<iostream>
#include<conio.h>
using namespace std;

class A //This is Base class and our task is to make this virtual
{
public:
void class_A()
{
cout<<"This is Base Class"<<endl;
}
};
class B: public virtual A // "public virtual" is the main concept of virtualization. In our program Class B and Class C both will be derived from Virtual Base Class.
{
public:
void class_B()
{
cout<<"This is Class B derived from class A"<<endl;
}
};
class C: public virtual A
{
public:
void class_C()
{
cout<<"This is class C derived from class A"<<endl;
}
};
class D: public B, public C
{
public:
void class_D()
{
cout<<"This class D derived from class B and C"<<endl;
}
};
int main()
{
D object;
object.class_A();
object.class_B();
object.class_C();
object.class_D();

return 0;
}

Output of the Program:

virtual base class output

LEAVE A REPLY

Please enter your comment!
Please enter your name here