In C++, why is private the default visibility for members of classes, but public for structs?
4 Answers
C++ was introduced as a superset of C. Structs were carried over from C, where the semantics of their members was that of public. A whole lot of C code exists, including libraries that were desired to work with C++ as well, that use structs. Classes were introduced in C++, and to conform with the OO philosophy of encapsulation, their members are private by default.

- 23,752
- 8
- 54
- 55
-
1Well, to be fair it's not strictly necessary for encapsulation to be all members private. With C++ inlining, the accessor methods can come very cheaply, but in many OOP languages given the overhead of a function call, people tend to use public access as it is cheaper. For finer control, one can use properties declarations if their lang support it. However, in native code, tracking variable changes is harder than managed languages, so it makes sense to set the attributes through a single point in the code. – progician Jan 02 '16 at 19:07
Because a class is a usual way of doing object orientation, which means that member variables should be private and have public accessors - this is good for creating low coupling. Structs, on the other hand, have to be compatible with C structs, which are always public (there is no notion of public and private in C), and don't use accessors/mutators.

- 513
- 1
- 7
- 21

- 12,034
- 15
- 57
- 79
Probably for backwards compatibility with C structs. This way structs declared in C code will continue to work the same way when used in C++ code.

- 7,637
- 34
- 29
Direct answer: Default visibility for struct in C++ is public and for class it's private.

- 1
- 1