VanQator
VanQator

Reputation: 53

Adding objects with defined operator doesn't work as I expect

The output is equal 20. Why the return value isn't 30?

class Myclass
{
public:
    int result;

    Myclass() { result = 10; }

    Myclass operator+ (Myclass& obj) {
        Myclass tempObj;
        tempObj.result += obj.result;
        return tempObj;
    }
};

int main()
{
    Myclass obj1, obj2, obj3;
    cout << (obj1 + obj2 + obj3).result;
}

If I correct understand, obj2 + obj3 return tempObj with result = 20. The next step is addition tempObj + obj1, that should return again tempObj but with result = 30.

Upvotes: 1

Views: 43

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311078

Within the operator

Myclass operator+ (Myclass& obj) {
    Myclass tempObj;
    tempObj.result += obj.result;
    return tempObj;
}

there is created local object tempObj the data member result of which is always initialized by 10.

So though the temporary object created by the sub-expression

obj1 + obj2

has the data member result is equal to 20 nevertheless its value is ignored.

It seems you mean

Myclass operator+ (Myclass& obj) {
    Myclass tempObj( *this );
    tempObj.result += obj.result;
    return tempObj;
}

Pay attention to that the parameter should have a constant reference type and the operator itself should be constant. For example

Myclass operator+ ( const Myclass& obj) const {
    Myclass tempObj( *this );
    tempObj.result += obj.result;
    return tempObj;
}

Upvotes: 1

songyuanyao
songyuanyao

Reputation: 172994

operator+ is performed from left to right, then obj1 + obj2 + obj3 is interpreted as (obj1 + obj2) + obj3, i.e. obj1 + obj2 is performed firstly. The temporary object returned by obj1 + obj2 contains result as 20, then the operator+ is performed with the temporary as the left operand, obj3 as the right operand. In the operator+, the left operand (i.e. *this) is not used at all, it always performs addition on the local object tempObj (whose result is 10) and the right operand (obj3's result is 10 too), then you got the result 20.

operator+ should perform addition on both the left and right operands. e.g.

Myclass operator+ (Myclass& obj) {
    Myclass tempObj(*this);
    tempObj.result += obj.result;
    return tempObj;
}

or

Myclass operator+ (Myclass& obj) {
    Myclass tempObj;
    tempObj.result = this->result + obj.result;
    return tempObj;
}

Upvotes: 1

Related Questions