I assume that I understand the meaning of "protected inheritance". However, after discussing this issue with one folk here, I feel a little confused now.
Here is my understanding of "protected inheritance" in c++
Assume the following class structure.
class Base {}
class SubClass : protected Base {}
1> If a subclass is defined as "protected BaseClass", then this subclass is no longer a subclass of the BaseClass. Instead, the BaseClass only serves as a utility tool for the subclass. In other word, if you cast SubClass* to Base*, SubClass& to Base&, or SubClass to Base, you should expect an error.
2> The major reason why people use protected inheritance is that the expected SubClass is NOT a subclass of the Base (For example, Car is not a subclass of Engine). While, in the same time, SubClass wants to call the functions defined in the Base class.
3> There is a good reason sometimes you prefer to using protected inheritance rather than define a member variable as an object of the Base. (but I don't remember in which case).
Please correct my comments if I am wrong.
thank you
For 1. - SubClass is still a subclass of Base. Protected inheritance is still inheritance. You are correct that automatic conversion from SubClass to Base is not possible, though.
SubClass sub;
Base* base(&sub);
gives
error C2243: 'type cast' : conversion from 'SubClass *' to 'Base *' exists, but is inaccessible
For 2. and 3. - the major reason people want this is to hide public/protected members of Base from clients of SubClass. Subclasses of SubClass CAN still see them. Contrast this with private inheritance which hides Base completely from subclasses and clients of SubClass - this would also meet your criteria in the last sentence of 2, but disallow any other external use of Base via SubClass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With