Skip to main content
3 of 3
added 553 characters in body
Christophe
  • 80.6k
  • 11
  • 132
  • 199

No, it's not required: Bjarne Stroustrup, explained how he naively added protected to C++ release 1.2, thinking to provide a useful feature to class developers, just to conclude only 5 years later that it was a nasty source of bugs, that fortunately no one was forced to use. Nowadays, he recommends not to use it.

The practical arguments against protected are the advantages of stronger encapsulation and the principle of the least knowledge:

  • Either a member is public and can be used by anybody;
  • Or the member is private and needs to be protected against external access.
  • A protected member, that requires careful usage (otherwise it would be public) can be misused as much by insiders (developers of derived class) as by anybody else.

Formal arguments confirm the practical experience. This has to do with the Liskov Substitution principle and more precisely its history rule:

We think it ought to be sufficient for a user to only know about the “apparent” type of the object; the subtype ought to preserve any properties that can be proved about the supertype.

Without going into the details of the quoted article, the protected members allow a derived class (subtype) to change the state of the base class object (supertype) in an unexpected manner, without relying on its public operations.

This being said, beware of the appearances and false promises. The Swift private is in-between private and protected in other languages:

Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. (...).

Christophe
  • 80.6k
  • 11
  • 132
  • 199