In the previous example, it is still possible to change the points variable directly, without using the provided methods. This is frowned upon by most programmers. If set and get methods are provided, they should be the only way to access the class variable. Suppose your class keeps a counter to know how many times the variable has changed. It would be easy to increase this counter every time the setPoints method is called. But the result cannot be trusted as long as you can also change the value without using this method.
Everyone makes mistakes, so it is better to make sure they cannot happen. Which can be done by making the class variables private: only the member functions of the class will be able to access private variables or methods. The methods themselves can be declared public, which allows you to use them from outside the class.
class score {
private:
int points = 0;
int counter = 0;
5
public:
int getPoints() {
return points;
}
10
score & setPoints(int points) {
this->points = points;
counter++;
return T;
15 }
}
score Score;
// somewhere in your application
20Score.points = 3; // won’t work
Score.setPoints(3); // does work and increases the counter