Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Should I make `operator+` const? And does it return a reference?

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?

like image 593
Brandon Miller Avatar asked Nov 16 '12 05:11

Brandon Miller


People also ask

Does const reference copy?

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 .

Is const reference type?

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.

Why do we return references in operator overloading?

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.

What is call by constant reference?

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.


1 Answers

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 ints do). In this case, addition for two integers returns a separate integer that is not a reference to neither one of the inputs.

like image 85
David Rodríguez - dribeas Avatar answered Sep 18 '22 13:09

David Rodríguez - dribeas