Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

class

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

like image 393
Naga Avatar asked Mar 28 '10 06:03

Naga


People also ask

Are data members private by default in C?

1 Answer. To explain: By default all the data members and member functions of class are private.

Why are data members 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 .

Are data members private by default?

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.

Why should data members of a class be 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.


2 Answers

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.

like image 129
Nick Dandoulakis Avatar answered Sep 21 '22 19:09

Nick Dandoulakis


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.

like image 31
paxdiablo Avatar answered Sep 17 '22 19:09

paxdiablo