how do I access "bar" from something like line 43
You can't.
because we were only able to retrieve the variable from the public function, and you could do that anyway?
Yes, but the important thing is that you can only access it through the public function. This is especially important when you are setting the value of it. Imagine you have this class:
class Vector2D {
private:
double x;
double y;
double magnitude;
public:
double getX();
double getY();
void setX(double newX);
void setY(double newY);
double getMagnitude();
};
Now, at all times, you want the data member "magnitude" to reflect the magnitude of the vector, so, anytime you update the values of x or y, you need to recalculate the magnitude. If you allowed access to x or y directly, you wouldn't be able to do that, but by controlling the access to x and y through these public functions, you can do the following:
double Vector2D::getX() {
return x;
};
double Vector2D::getY() {
return y;
};
void Vector2D::setX(double newX) {
x = newX;
magnitude = sqrt( x * x + y * y );
};
void Vector2D::setY(double newY) {
y = newY;
magnitude = sqrt( x * x + y * y );
};
double Vector2D::getMagnitude() {
return magnitude;
};
See how I can easily make sure that the value of "magnitude" is always consistent with the values stored in x and y, because anytime the user wants to modify those …