22 Declare data members private

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 than public.
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容