Should you ever use protected member variables?

John Channing picture John Channing · Aug 31, 2008 · Viewed 64.9k times · Source

Should you ever use protected member variables? What are the the advantages and what issues can this cause?

Answer

Allain Lalonde picture Allain Lalonde · Aug 31, 2008

Should you ever use protected member variables?

Depends on how picky you are about hiding state.

  • If you don't want any leaking of internal state, then declaring all your member variables private is the way to go.
  • If you don't really care that subclasses can access internal state, then protected is good enough.

If a developer comes along and subclasses your class they may mess it up because they don't understand it fully. With private members, other than the public interface, they can't see the implementation specific details of how things are being done which gives you the flexibility of changing it later.