Is there any particular reason that all data members in a class are private by default in C++?
1 Answer. To explain: By default all the data members and member functions of class are private.
Data members may be private or public, but are usually held private so that values may only be changed at the discretion of the class function members. In the example below, the class C contains two a private data member of type int , and a public data member of type pointer to char .
Data members of a class are by default private. Member functions of a class are by default public. A private function of a class can access a public function within the same class. Member function of a class are by default private.
By making the variable a private data member, you can more easily ensure that the value is never negative. On the other hand, if the variable is public, another class could change it to a negative value which can cause other parts of the code to crash.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With