-1

i tring to learn operator overloading and i dont get somthing. when i do:

    class Point
    {
public:
    void show(){ cout << "the point is(" << _x << ", " << _y << ")" << endl;}
    void print(){ _x = 1; _y = 1; }
    void operator+=(const Point &other){
        _x = other._x + 100;
        _y = other._y + 100;
    }

private:
    int _x;
    int _y;
};

int main()
{
    Point p1;
    Point p2;
    p1 +=p2;
    p2.show();
    getchar();
}

its work. but when i change it to:

Point p1;
Point p1;
Point p2;
Point p3;
p1 +=p2 +=p3;

its doesnt and i need to return (*this). why is it? if someone can explain it to me i will be greatfull.. thanks :)

mikel bubi
  • 123
  • 1
  • 1
  • 7
  • 1
    Possible duplicate of [Operator overloading](http://stackoverflow.com/questions/4421706/operator-overloading) –  Jul 06 '16 at 13:12

3 Answers3

3

When you do

p1 +=p2;

You're actually calling

p1.operator+=(p2)

It returns void though it shouldn't (see Assignment operators), but it's not the problem here since you're not using the return value anyway.

But when you do

p1 += p2 += p3;

It's actually

p1.operator+=(p2.operator+=(p3))

and now returning void is a problem since operator += expects a value as an argument.

buld0zzr
  • 962
  • 5
  • 10
2

The reason you need to return a reference here is that p2 +=p3 does not evaluate to p2 after p3 has been added to it. What it does evaluate to is the return value of operater+= of Point which is void. You cannot add void to p1 so you get the error.

Another way of looking at p2 +=p3 is p2.operator+=(p3). Here we can clearly see we do not get p2 but instead we get what p2.operator+=(p3) returns.

This is why we return a reference. It allows us to chain the results together like you are trying to do. If you do not return a reference then you have to break the chain.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
1

Your operator += has return type void.

void operator+=(const Point &other);
^^^^^

So a call of this operator may not be used in other call of the operator +=.

Otherwise it would look like

Point p;

p += void;

A valid definition of the operator could look like

Point & operator +=( const Point &other )
{
    _x += other._x;
    _y += other._y;

    return *this;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335