+ 5

Why ever use private?

So, classes in C++ can have public and private variables or methods. But, what's the point of having any private things? Why not just have them be all public?

12th Nov 2016, 2:02 AM
Keto Z
Keto Z - avatar
3 Réponses
+ 16
A public member can be accessed from outside the class, which for practical considerations means "potentially anywhere". If something goes wrong with a public field, the culprit can be anywhere, and so in order to track down the bug, you may have to look at quite a lot of code. A private member, by contrast, can only be accessed from inside the same class, so if something goes wrong with that, there is usually only one source file to look at. If you have a million lines of code in your project, but your classes are kept small, this can reduce your bug tracking effort.
12th Nov 2016, 5:23 AM
Remmae
Remmae - avatar
+ 8
Some of the data a class has isn't needed outside the class, or should not be modified from anywhere. The same goes for some methods. For example, if you had a class for an Employee, you wouldn't want anything to be able to directly modify what their wage is or change their ID number, right? So those sorts of things would be private. But they could enter their hours worked, position, or something like that, which would be used to determine their wage. That data the class needs to get would be public. Some methods are only part of a whole action. Ex: You can call a method to change an Employee's address. It might be split into simpler methods, to get the street, ZIP, city, etc., and then put them together. There's no reason to be able to call the half-steps.
12th Nov 2016, 3:39 AM
Tamra
Tamra - avatar
- 1
we will be transparency ;)
28th Oct 2017, 12:24 PM
Edi