While I've seen rare cases where private inheritance was needed, I've never encountered a case where protected inheritance is needed. Does someone have an example?
People here seem to mistake Protected class inheritance and Protected methods.
FWIW, I've never seen anyone use protected class inheritance, and if I remember correctly I think Stroustrup even considered the "protected" level to be a mistake in c++. There's precious little you cannot do if you remove that protection level and only rely on public and private.
There is a very rare use case of protected inheritance. It is where you want to make use of covariance:
struct base {
virtual ~base() {}
virtual base & getBase() = 0;
};
struct d1 : private /* protected */ base {
virtual base & getBase() {
return this;
}
};
struct d2 : private /* protected */ d1 {
virtual d1 & getBase () {
return this;
}
};
The previous snippet tried to hide it's base class, and provide controlled visibility of bases and their functions, for whatever reason, by providing a "getBase" function.
However, it will fail in struct d2
, since d2
does not know that d1
is derived from base
. Thus, covariance
will not work. A way out of this is deriving them protected, so that the inheritance is visible in d2.
A similar example of using this is when you derive from std::ostream
, but don't want random people to write into your stream. You can provide a virtual getStream
function that returns std::ostream&
. That function could do some preparing of the stream for the next operation. For example putting certain manipulators in.
std::ostream& d2::getStream() {
this->width(10);
return *this;
}
logger.getStream() << "we are padded";
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