Wednesday, April 6, 2016

Protected Inheritance in C++

Understanding the concept of Protected Inheritance in C++.
A special mention of visibility label protected:
We have just seen how to increase the capabilities of an existing class without modifying it. We have also seen that a private member of a base class cannot be inherited and therefore its is not available for the derived class directly. What do we do if the private data needs to be inherited by a derived class? This can be accomplished by modifying the visibility limit of the private member by making it public. But, this would make it accessible to all the other functions of the program, thus, eliminating the advantage of data hiding.
C++ provides a third visibility modifier, protected which serves a limited purpose in inheritance. A member declared as protected is accessible by the member functions within its class and any class immediately derived from it. It cannot be accessed by the function outside these two classes. A class can now use all the three visibility modes as illustrated below:
When a protected member is inherited in public mode, it becomes protected in the derived class too, and therefore is accessible by the member functions of the derived class. It is also ready for the further inheritance.
A protected member, inherited in the private mode derivation, becomes private in the derived class. Although, it is available to the member functions of the derived class, it is not available for further inheritance (since private members cannot be inherited).
The keywords private, public and protected may appear in any order and in any number of times in the declaration of a class.
For example:
is a valid class definition.
However, the normal practice is to use them as follows:
A special mention of Protected Inheritance:
In previous posts, we mentioned about defining of derived class by using keywords private and/or public as visibility mode. In addition to that, we can also use the keyword protected as visibility mode in the defining of the derived class. Such inheritance using the visibility mode protected is known as protected inheritance.
In protected inheritance, public members of base class become protected in derived class as also the protected members of the base class become protected in the derived class. However, as usual, private members of a base class cannot be inherited.
Example:

0 comments:

Post a Comment