When a class overloads operator+
, should it be declared const since it does not do any assignment on the object?
Also, I know that operator=
and operator+=
return a reference because an assignment is made. But, what about operator+
? When I implement it should I make a copy of the current object, add the given object to that, and return that value?
Here is what I have:
class Point
{
public:
int x, int y;
Point& operator += (const Point& other) {
X += other.x;
Y += other.y;
return *this;
}
// The above seems pretty straightforward to me, but what about this?:
Point operator + (const Point& other) const { // Should this be const?
Point copy;
copy.x = x + other.x;
copy.y = y + other.y;
return copy;
}
};
Is this a correct implementation of the operator+
? Or is there something I am overlooking that could cause trouble or unwanted/undefined behavior?