Loading....
Coupon Accepted Successfully!

 

Virtual Base Classes

To overcome the ambiguity occurring due to multipath inheritance, the C++ provides the keyword virtual. The keyword virtual declares the specified classes virtual. The example given below illustrates the virtual classes:
 

class A1

{

protected:

int a1;

};

class A2 : virtual public A1 // virtual class declaration

{

protected:

int a2;

};

class A3: virtual public A1 // virtual class declaration

{

protected:

int a3;

};

class A4: public A2,A3

{

int a4;

};


When classes are declared as virtual, the compiler takes essential caution to avoid the duplication of member variables. Thus, we make a class virtual if it is a base class that has been used by more than one derived class as their base class.


Consider another example that will give you a clear idea of virtual classes as well as the necessary care to be taken while declaring virtual classes.
  1. A base class cannot be specified more than once in a derived class.
     
     
    Here, class A is specified twice. Hence, it is an illegal declaration.
  2. A base class can be indirectly passed to the derived class more than once.
     
     
    In the above case (b), each object of class J will contain two sub-objects of class A through classes L and K.
  3. The case (b) causes problems. To avoid duplication, we can add the keyword virtual to a base class specifier.
     
     
    The keyword virtual always appears before the class name. A is now a virtual base class, and class J has only one sub-object of class A.
11.11 Write a program to declare virtual base classes. Derive a class using two virtual classes.
 
OUTPUT
Enter values for a1, a2,a3 and a4 : 5 8 7 3
a1= 5 a2 = 8 a3 = 7 a4 = 3
 
Explanation: In the above program, the classes A1, A2, A3, and A4 are declared, and each contains one protected member variable. The class A4 has two member functions get() and put(). The get() function reads integers through the keyboard. The put()function displays the contents of the member variables on the screen. The classes A2 and A3 are derived from class A1. While deriving these two classes, the class A1 is declared as virtual as per the following statements:
 

class A2: public virtual A1 // derivation of class A2

class A3: public virtual A1 // derivation of class A3

class A4: public A2,A3 // derivation of class A4


The
class A4 is derived from two classes A2 and A3 as per the statement (c). In function main(), the object a of class A4 invokes the member function get() and put(). The output of the program is as shown above.





Test Your Skills Now!
Take a Quiz now
Reviewer Name