2.1.2 When to use it?

protected inheritance is useful when everything exposed to descendents need to remain exposed, but all public members need to be restricted. The big question is, why don’t we make public members of the superclass protected to begin with? In our example, why don’t we make member k protected to begin with?

There can be several reasons. First of all, the superclass may not be under our control. For example, ostream is a predefined class from iostream. If we want to derive a subclass to handle a particular kind of output files, and want to restrict the consumers from using the basic output methods, then we can use protected inheritance. In other words, we can define our own subclass as in listing 2.


Listing 2:ostreamsubclass
 
1class XOStream : protected ostream 
2{ 
3  public
4    XOStream & << (const X &whatever); 
5};

This way, all the default output operators for integers, strings, and etc. are all hidden from the public. However, the new output operator for type X is exposed. In other words, any objects created from XOStream only knows how to output objects of class X. We may need to do this to make sure the output stream conform to a particular syntax.

Note that all subclasses of XOStream can still use the output operators for basic types.