Virtual Base ClassesTo 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:
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.
- A base class cannot be specified more than once in a derived class.
- A base class can be indirectly passed to the derived class more than once.
- The case (b) causes problems. To avoid duplication, we can add the keyword virtual to a base class specifier.
Enter values for a1, a2,a3 and a4 : 5 8 7 3
a1= 5 a2 = 8 a3 = 7 a4 = 3Explanation: 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:
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.