Archived

This topic is now archived and is closed to further replies.

What's wrong with this segment of code?

This topic is 5125 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

class Point2d { public: Point2d(float x = 0.0, float y = 0.0) : _x(x), _y(y) {}; float x() { return _x; } float y() { return _y; } void x(float newX) { _x = newX; } void y(float newY) { _y = newY; } void Point2d::operator += ( const Point2d & rhs) { _x += rhs.x(); _y += rhs.y(); } protected: float _x, _y; }; If I eliminate the keyword const, it will be ok. But why?

Share this post


Link to post
Share on other sites
i think you should declare the methods x() and y() as const, so the compiler knows they are not changing any contents of the class:


class Point2d {
public:
Point2d(float x = 0.0, float y = 0.0)
: _x(x), _y(y) {};

float x() const { return _x; }
float y() const { return _y; }

void x(float newX) { _x = newX; }
void y(float newY) { _y = newY; }
void Point2d::operator += ( const Point2d & rhs) {
_x += rhs.x();
_y += rhs.y();
}

protected:
float _x, _y;
};

Share this post


Link to post
Share on other sites