Why use getters to const private members instead of making them public?

57 views Asked by At

Suppose I have a simple class that defines a Circle object:

class Circle {
public:
    Circle(const double x): radius(x) { ; }
    const double getRadius() const { return radius; }

private:
    const double radius;

};

This seems like a common convention and subscribes to the OO principle of data-hiding. My question is why do this? Would it not be simpler to make radius a public member? For a mutable member, this would obviously be a bad idea, since anyone could modify the circle's radius, but since it's const, I see no need to make it private. Would it be acceptable to do something like this?:

class Circle {
public:
    Circle(const double x): radius(x) { ; }
    const double radius;
};
0

There are 0 answers