why not just make it public? |
I ask because the book I'm reading to learn C++ indicates that it's best practice to keep your class members private because it's "safer", but it doesn't elaborate. |
The book is right, because if you make everything public it is just like having global variables.
In C++, It is best to make all your member variables private or protected, then provide public functions to set and get the member variables.
Here's a somewhat complex example:
Say you want to have the ability to create an arc object by sending it 3 2d points. The 3 points are the beginning of the arc, a point on the arc, and an end point; we might name them A, B, C. Quick geometry lesson: Draw lines AB and BC. The perpendicular Bisectors of these intersect at the center of the arc.
To do these calcs you might need local variable like ABDist, ABBisectorAngle etc.
Now if I was to give you an arc object, you would probably be only interested in: CenterPoint, Radius, StartPoint, EndPoint, say (there are lots of other variations).
So you make everything private or protected, then provide public functions that return only the things that you want. i.e getCenterPoint, getRadius, getStartPoint, getEndPoint.
With set functions, it's the same, and in this case, if you change one thing, you have to recalc all the others.
If everything was public, then changing the CenterPoint would invalidate the others.
Private means that only that class has access to the variables via the code in the member functions, and not via the dot operator. They are inherited, but there won't be access to them in derived classes
Protected means that derived classes also have access to the base's private members via the code in the member functions, and not via the dot operator.
Hope this helps