How private really works in classes c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How private really works in classes c++

Since we have 3 access specifiers in c++ one of those is the private access specifier. My question is if we declared everything as private we still going to have to create public functions to access them inside main and we can modify what's in private through main and change things in it. So what is the benefit of using private when we still should make public variables or functions to access the private stuff and we can still modify them and change them from outside the class when they're private ?

5th Jul 2020, 7:28 AM
The Unknown
The Unknown - avatar
3 Answers
+ 4
The Unknown private means you can only access in the class. You can access the private methods or variable inside the class only and inside any public method. To call in main you need to create public method in class.
5th Jul 2020, 7:43 AM
A͢J
A͢J - avatar
+ 3
Hi The Unknown, The use of private specifier is a way to implement encapsulation, one of the pillar of object oriented programming. This hides the way an class is implemented. The caller object only need to know the public method to access a value, and privately, the value could be a private variable, or calculated, or requested from another object... the caller does not need to know and should not be impacted if the structure of the called object class changes.
5th Jul 2020, 7:47 AM
ifl
ifl - avatar
+ 2
Access the member functions with in the Class.
6th Jul 2020, 2:14 AM
Rajab Shabbir
Rajab Shabbir - avatar