C++ - Should I make `operator+` const? And does it return a reference?
c++, oop, operator-overloading, operators, reference
Solution
Better than that, you should make it a free function:
Point operator+( Point lhs, const Point& rhs ) { // lhs is a copy
lhs += rhs;
return lhs;
}
But yes, if you leave it as a member function it should be `const` as it does not modify the left hand side object.
Regarding whether to return a reference or a copy, the advice for operator overloading is do as fundamental types do (i.e. do as `int`s do). In this case, addition for two integers returns a separate integer that is not a reference to neither one of the inputs.
Problem
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?