I have several objections to the premise and wording of this rule
Upon this rule SonarQube advises
Make this inheritance “public”.
private and public inheritance have fundamentally different meaning (“is-implemented-in-terms-of” vs. “is-a” relationship). To replace one by the other, albeit it is technically possible, is semantically infeasible and is not good advise.
While it is possible for inheritance to be non-
public
, it is rarely justified and complicates the use of the derived class. For instance, inherited member visibility is diminished and implicit andstatic_cast
casts from the derived class to the base class will not work.
While I agree that private inheritance has fewer use cases than public inheritance and should rarely be used, it does not complicate the use of the derived class. It allows the use exactly in the way it is supposed to. Both examples of how it complicates the use are wrong.
- Visibility is diminished by design, if you don’t want this, this is not a use case for private inheritance
- The purpose of private inheritance is not to enable polymorphism, therefore implicit and
static_cast
casts from the derived class to the base class do not work by design.
It is sometimes used to limit the base class functionality available in the derived class.
This is the whole point of encapsulation. To limit what external users (such as the derived class) can do.
When that is the desire, composition should be used instead.
While I would agree that composition should be preferred when possible, there are semantic differences between private inheritance and composition. It is not always possible/sensible to replace one by the other.