OOPS - [C++ Virtual Base Class]

♠ Posted by Unknown in at 04:00

Virtual Base Class


When all the three kinds of inheritance, namely, multilevel, multiple, and hierarchical inheritance, are involved. This is illustrated in below figure. The ‘child’ has two direct base classes ‘parent1’ and ‘parent2’ which themselves have a common base class ‘grandparent’. The ‘child’ inherits the traits of ‘grandparent’ via two separate paths. It can also inherit directly as show by the broken line. The ‘grandparent’ is sometimes referred to as indirect base class.
                      
Image: Virtual Base Class
                                                 

Inheritance by the ‘child’ as shown in figure might pose some problems. All the public and protected members of ‘grandparent’ are inherited into ‘child’ twice, first via ‘parent1’ and again via ‘aprent2’. This means, ‘child’ would have duplicate sets of the members inherited from ‘grandparent’. This introduces ambiguity and should be avoided.
The duplication of inherited members due to these multiple paths can be avoided by making the common base class as virtual class.
When a class is made a virtual base class, C++ takes necessary care to see that only one copy of that class is inherited, regardless of how many inheritance paths exists between the virtual base class and a derived class.

2 comments:

Can i have simple example of Virtual Base Class?

Simple example means? Virtual Base class happened when above kind of inheritance done like, There is one super base class members is derived on two ways called parent-1 and parent-2 to the grand child class then super base class need to declare virtual base class. So, If this kind of hierarchical structure is not built up in example then no need to declare virtual base class.

Post a Comment