About operator + overloading

Viewed 47

I have the following code snippet:

#include <iostream>

using namespace std;

struct Integer{
    int x;
    Integer(const int val) : x(val){}
    friend Integer operator+(Integer& i, Integer& j){
        return Integer(j.x + i.x);
    }
    friend std::ostream& operator<<(std::ostream& o, Integer i){
        o << i.x;
        return o;
    }
};

int main(){
    Integer i(25), j(5), k(2020);
    std::cout << (i + j + k);

    return 0;
}

Why doesn't it compile ? The error I get is "No match for 'operator+' (operand types are Integer and Integer)". Why does that happen ? Isn't the calculation done from right to left ? Isn't (j + k) an Integer(2025), plus i which is an Integer(25) shouldn't the result be the obvious one, meaing 2050 ? Where am I wrong ? Also, my goal is to tell why the that code snippet does not compile, and how can I make it compile by modifyng at most one line of code. (this is what they will ask us at our exam). Thanks !

1 Answers

operator+ returns by-value, what it returns is an rvalue, which can't be bound to lvalue-reference to non-const, i.e. can't be passed to operator+ as argument for the next cacluation.

Change the parameter type of operator+ to lvalue-reference to const, which could bind to rvalues.

friend Integer operator+(const Integer& i, const Integer& j){
//                       ^^^^^             ^^^^^
    return Integer(j.x + i.x);
}
Related