Rewording of rule cpp:S3469

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 and static_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.

Hi @pzsifkovits-knapp,

You know that the C++ community is very fragmented, and different people hold very different opinions.

I totally agree with all the arguments that you shared, still, some people (probably with a strong background in other languages) believe that the only inheritance worth using is the public one. This is why we are in this situation: We provide this rule for people who want to enforce this code style in their codebase, but it is not enabled by default. This is an opt-in (and I would not opt-in to this rule for my own codebases, and I suggest you don’t either).

About the message Make this inheritance “public”., I think that one target of this rule is also newcomers who just forgot to say public when specifying a base class in a class. This is not likely to be detected in SonarQube Server or SonarQube Cloud, because the code will not work as expected before being committed, but it can be useful in SonarQube for IDE, where it can help detect a typo that, from my experience in teaching, usually keeps beginners totally dumbfounded.

Hope this helps!

1 Like

Thanks for the clarification. I did not recognize that this is opt-in. It started popping-up lately in my code base, so I thought this is new, but probably someone must have turned it on.