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

2019-03-19 19:39发布

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

标签: c++ class
5条回答
男人必须洒脱
2楼-- · 2019-03-19 19:56

Because otherwise there would be no difference at all between class and struct?

查看更多
淡お忘
3楼-- · 2019-03-19 20:08

The Design and Evolution of C++

2.10 The Protection Model

Before starting work on C with Classes, I worked with operating systems. The notions of protection from the Cambridge CAP computer and similar systems - rather than any work in programming languages - inspired the C++ protection mechanisms. The class is the unit of protection and the fundamental rule is that you cannot grant yourself access to a class; only the declarations placed in the class declaration (supposedly by its owner) can grant access. By default, all information is private.

查看更多
Luminary・发光体
4楼-- · 2019-03-19 20:12

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.

查看更多
贪生不怕死
5楼-- · 2019-03-19 20:14

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.

查看更多
祖国的老花朵
6楼-- · 2019-03-19 20:17

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.

查看更多
登录 后发表回答