Is there any particular reason that all data members in a class are private by default in C++?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
Because otherwise there would be no difference at all between
class
andstruct
?The Design and Evolution of C++
2.10 The Protection Model
In a word, encapsulation. The goal is to have private implementation details (such as data members) be private. Only explicitly public API is made available to clients of the class.
Because it's better to be properly encapsulated and only open up the things that are needed, as opposed to having everything open by default and having to close it.
Encapsulation (information hiding) is a good thing and, like security (for example, the locking down of network services), the default should be towards good rather than bad.
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.