Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any examples where we *need* protected inheritance in C++?

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?

like image 240
OysterD Avatar asked Aug 28 '08 08:08

OysterD


Video Answer


2 Answers

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.

like image 102
Mats Fredriksson Avatar answered Oct 25 '22 20:10

Mats Fredriksson


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";
like image 5
Johannes Schaub - litb Avatar answered Oct 25 '22 19:10

Johannes Schaub - litb