Cy Edmunds said:
class Point
{
private:
int m_x, m_y;
public:
Point(int i_x, int i_y) : m_x(i_x), m_y(i_y) {}
int x() const {return m_x;} // read-only access
int y() const {return m_y;} // ditto
};
That's pretty minimal but is still a valid object and has no get/set
pairs.
No "pairs", but it does have "getters". (Which is fine...I'm just
commenting on your statement, not your solution.)
You can still change the internal state using the constructor:
Point p(2, 3);
std::cout << p.x() << '\n'; // prints a 2
p = Point(5, 3);
This does not construct a new p object, if that's what you're implying. It
creates an unnamed temporary using the parameterized constructor, and then
calls the assignment operator to copy the members to p, and then destroys
the temporary. (I forget if the compiler is allowed to somehow optimize
some of that away, however.) (Oh, and it's ok in this case, but would be a
problem if the members were const, or if for some reason the
compiler-generated assignment operator weren't sufficient to the task, such
as if there were pointer members involved.)
std::cout << p.x() << '\n'; // prints a 5
Syntactically it is not entirely unreasonable to think of Point(5, 3) as a
constant of type Point although that is not really what it is. Anyway I
almost always prefer this paradigm to get/set pairs.
What if construction is expensive? (Not that any of this matters here,
since the OP wasn't really interested in changing the values after
construction in the first place.)
Personally, I think Victor's idea of just making the members const it the
easiest and most obvious way.
-Howard