The main reason to make data members of a class private is to make it easy to trace bugs in the program or prevent accidental changes.
But public functions of the class can be called anywhere in the whole program and change the data members value. So wouldn't tracing bugs be as tedious as when making member public?
The point is that there's a single point in the code that actually does change the value, but does it on behalf of the code that wants it changed.
Quick example:
class A
{
public:
void set_x(int x) { m_x = x; }
int m_y;
private:
int m_x;
};
Suppose we know that m_x
and m_y
should always be between -100 and 100, and some bug is causing both to be 2000.
There are various ways of finding the code that causes the bug:
We can set breakpoints.
With m_x
, we set one, in set_x
- with m_y
, we need to find every assignment to it throughout the code and set a breakpoint there (and someone may use a pointer or reference to it, so we can't just search for "m_y" - we need to find every potential assignment).
Or, we could insert some validation code and throw an exception when things go bad.
Just as before, we need to do that in one place with m_x
, but need to locate every potential reference to m_y
throughout the code.