Why are data members private by default in C++?

后端 未结 5 1263
挽巷
挽巷 2021-02-06 01:23

Is there any particular reason that all data members in a class are private by default in C++?

5条回答
  •  甜味超标
    2021-02-06 02:09

    The reasoning is that the public parts of a class should be explicitly made public.

    The interesting thing about this (to me anyway) is that the first line after the opening brace of many, many class definitions is public:. Most readers of a class are interested in the public bits, since that's what they interact with, and so many class definitions have their public bits first anyway.

    C++'s access specifiers apply to the range that follows them - I think Java and C#'s technique of having each member to specify the visibility of the member (with a sensible default) is preferable.

提交回复
热议问题