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?
Not just a copy; it is also a const copy. So you cannot modify it, invoke any non-const members from it, or pass it as a non-const parameter to any function. If you want a modifiable copy, lose the const decl on protos .
Technically speaking, there are no const references. A reference is not an object, so we cannot make a reference itself const. Indeed, because there is no way to make a reference refer to a different object, in some sense all references are const.
you can see that x will be printed first , so if you return by value in overloading of << operator , return value will not be "lvalue" , while returning by refrence is a lvalue , so cascading of << operator can be achieve. Save this answer.
call by value will copy all the elements of the object it does protect the callers argument because if you are going to change something it is only a copy you are changing. calling by const reference does not copy elements but because of the "const" it will protect caller's argument. You const reference.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With