When I can do:
struct point_t { double x, y ; };
Why do I do:
1 2 3 4 5 6 7 8 9
|
class point_t {
private:
double x,y;
public:
double getX() const ; /* { return x ; } */
double gety() const ; /* { return y ; } */
bool changeX(double val); /* { x = val ; } */
bool changeY(double val); /* { y = val ; } */
};
|
Because I am extremely stupid.
> why, people can always change x and y through public functions.
> And it is clumsy, 4 more functions will consume much more memory and cpu time, right?
It won't really consume more memory and cpu time (the compiler knows what is going on), but it is clumsy; it introduces mindless verbosity, which is always more expensive in terms of programmer time and programmer memory.
In languages which are C based, there are reasons why we might want to restrict access to something that we have exposed; made programatically visible.
One, we might have identified an invariant which we must maintain for program correctness. For instance:
1 2 3 4 5 6 7 8
|
struct wall_clock
{
// ....
private:
int hour ; // invariant: must be in [0,23]
int minute ; // invariant: must be in [0,59]
};
|
Even if the member variables
hour and
minute are visible to every user, we would want to prevent unrestricted access to them (
private) because our design requires that we must ensure that the invariant in maintained at all times.
Two, we might want to change the implementation at some point in future without breaking user code.
1 2 3 4 5 6 7 8 9
|
struct wall_clock
{
// ....
// same interface as earlier
private:
int seconds_since_midnight ; // invariant: must be in [0,24*60*60)
// but a different implementation
};
|
Three, we may want (very often we do want) the logical interface to reflect the needs of the user while the implementation details reflect the needs of the implementor. For instance:
1 2 3 4 5 6 7 8
|
struct person
{
int age_in_years() const ;
// ....
private:
date date_of_birth ;
};
|
If none of these concerns are applicable, a
point class with private data is pointless.