On the one hand, if data members are not public, the only way for clients to access an object is via member functions. If everything in the public interface is a function, client won't have to try to remember whether to use parentheses when they want to access a member of the class. They will just do it, because everything is a function.
On the other hand, If you make a data member public, everybody has read-write access.
Hiding data members behind functional interfaces can offer all kinds of implementation flexibility.You can ensure that class invariants are always maintained, because only member functions can affect them.
If you do not hide such decisions, you will soon find that even if you own the source code to a class, your ability to change anything public is extremely restricted, because too much client code will be broken.The same conditions with the protected
.
Conclusion
- Declare data members
private
. It gives clients syntactically uniform access to data, affords fine-grained access control, allows invariants to be enforced, and offers class authors implementation flexibility. -
protected
is no more encapsulated thanpublic
.