C++ Virtual Class

Advertisements

C++ Virtual Base Class

Virtual base class is used in situation where a derived have multiple copies of base class. Consider the following figure:




Example without using virtual base class


       #include<iostream.h>
       #include<conio.h>

       class ClassA
       {
              public:
              int a;
       };

       class ClassB : public ClassA
       {
              public:
              int b;
       };
       class ClassC : public ClassA
       {
              public:
              int c;
       };

       class ClassD : public ClassB, public ClassC
       {
              public:
              int d;
       };

       void main()
       {

		  ClassD obj;

		  obj.a = 10;        //Statement 1, Error occur
		  obj.a = 100;      //Statement 2, Error occur

		  obj.b = 20;
		  obj.c = 30;
		  obj.d = 40;

		  cout<< "\n A : "<< obj.a;
		  cout<< "\n B : "<< obj.b;
		  cout<< "\n C : "<< obj.c;
		  cout<< "\n D : "<< obj.d;

	   }

   Output :

              A from ClassB  : 10
              A from ClassC  : 100
              B : 20
              C : 30
              D : 40

In the above example, both ClassB & ClassC inherit ClassA, they both have single copy of ClassA. However ClassD inherit both ClassB & ClassC, therefore ClassD have two copies of ClassA, one from ClassB and another from ClassC.

Statement 1 and 2 in above example will generate error, bco'z compiler can't differentiate between two copies of ClassA in ClassD.

To remove multiple copies of ClassA from ClassD, we must inherit ClassA in ClassB and ClassC as virtual class.

Example using virtual base class


       #include<iostream.h>
       #include<conio.h>

       class ClassA
       {
              public:
              int a;
       };

       class ClassB : virtual public ClassA
       {
              public:
              int b;
       };
       class ClassC : virtual public ClassA
       {
              public:
              int c;
       };

       class ClassD : public ClassB, public ClassC
       {
              public:
              int d;
       };

       void main()
       {

		  ClassD obj;

		  obj.a = 10;        //Statement 1
		  obj.a = 100;      //Statement 2

		  obj.b = 20;
		  obj.c = 30;
		  obj.d = 40;

		  cout<< "\n A : "<< obj.a;
		  cout<< "\n B : "<< obj.b;
		  cout<< "\n C : "<< obj.c;
		  cout<< "\n D : "<< obj.d;

	   }

   Output :

              A : 100
              B : 20
              C : 30
              D : 40

According to the above example, ClassD have only one copy of ClassA and statement 4 will overwrite the value of a, given in statement 3.

Advertisement