In hierarchical inheritance we have seen that a base class is inherited by many derived classes. If derived class is obtained from these derived class then a situation arises where compiler find’s ambiguity. Ambiguity is state where duplication of data arises. As a counter measure for this situation we take the help of virtual base class. If we use the keyword virtual while inheriting a class, then complier avoids the duplication of same data from different classes.
The Keyword for usage of virtual base class is virtual and the syntax is:
class derived_name: virtual mode base_name;
class derived_name: mode virtual base_name;
Let us consider an example where we shall write a program with-out use of virtual base class and then with virtual base class.
#include iostream.h #include conio.h class base { Public: int I; }; class derived1: public base { Public: int j; }; class derived2: public base { Public: int k; }; class derived3:public derived1,public derived2 { Public: int sum; }; void main() { Clrscr(); derived ob3; ob3.i=2; ob3.j=9; ob3.k=4; ob3.sum=ob3.i+ ob3.j+ ob3.k; cout<<”Sum of those numbers is:”<<ob3.sum; getch(); }
According to our knowledge everything is correct, since every syntax concept is perfectly applied but whenever control passes to the statement ob3.i=2 then the case of ambiguity arises. There the compiler shows ambiguity. To remove this error need to use the keyword virtual and the concept of virtual base class. Know we shall re-write the program using virtual base classes.
#include iostream.h #include conio.h class base { Public: int I; }; class derived1: virtual public base { Public: int j; }; class derived2: public virtual base { Public: int k; }; class derived3:public derived1,public derived2 { Public: int sum; }; void main() { Clrscr(); derived ob3; ob3.i=2; ob3.j=9; ob3.k=4; ob3.sum=ob3.i+ ob3.j+ ob3.k; cout<<”Sum of those numbers is:”<<ob3.sum; getch(); }
Now the ambiguity is removed and program is executed perfectly. Whenever we using hierarchical inheritance we need to take the help of virtual base class.