Types of inheritance:
The derived class inherits some or all of the traits from the base class. A class can also inherit properties from more than one class or from more than one level. A derived class with only one base class is called single inheritance and one with several base classes is called multiple inheritance. On the other hand, the traits of one class may be inherited by more than one class. The process is known as hierarchical inheritance. The mechanism of deriving a class from another ‘derived class’ is known as multilevel inheritance. The following figure shows various forms of inheritance that could be used for writing extensible programs. The direction of arrow indicates the direction of inheritance.
As we mentioned earlier, the ‘public’ qualifier, used when deriving one class from another specific that all public members of the base class become public members of the derived class. All members of the base class are inherited as they are - public as public, and protected as protected. All these access restrictions of members of the base class remain the same, whether they are accessed from the object of the base class or that of the derived class.
The ‘private’ qualifier:
If the ‘private’ is used when deriving a class, all the public and protected members of the base class become private members of the derived class, i.e., the members of the base class can be accessed only within the derived class, they can’t be accessed through an object of the derived class. The private qualifier is rarely used. It is used to end a hierarchy of classes.
The ‘protected’ qualifier:
This qualifier, when used while deriving a class, specifies that all public and protected members of the base class must become protected members of the derived class. This means that, like a private inheritance, these members can’t be accessed through objects of the derived class, whereas, unlike a private inheritance, they can still be inherited and accessed by subsequent derived classes. In other words, protected inheritance does not end a hierarchy of classes, as private inheritance does.
The following table illustrates this:
(*) these members can’t be accessed from within the derived class also.
Private members of the base class are not accessible from within the derived class, whatever be the type of inheritance. They just add to the derived class member list and can be accessed only through the inherited public or protected member functions of the base class.
Comments/Suggestions are invited. Happy coding......!
Comments Post a Comment