default visibility of C++ class/struct members

C++ClassStructMember

C++ Problem Overview


In C++, why is private the default visibility for members of classes, but public for structs?

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

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.

Solution 3 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionS IView Question on Stackoverflow
Solution 1 - C++Oren TrutnerView Answer on Stackoverflow
Solution 2 - C++a_m0dView Answer on Stackoverflow
Solution 3 - C++Karl VoigtlandView Answer on Stackoverflow