0

I have the following code to overload operator+, which works fine when the program gets executed.

In the main() function, when I re-write the statement to call the overloaded operator+ from res= t + t1 + t2, which works fine, to res = t + (t1 + t2), it does not work anymore. Can anyone provide me a solution, along with the reason?

A solution already found is to update the signatures of the operator+ from Test operator +(Test &a) to Test operator +(const Test &a). Here, I have used the const keyword in the parameter list.

#include <iostream>
using namespace std;

class Test
{
private:
    int num;

public:
    Test(int v)
    {
        num = v;
    }

    Test operator+(Test &a)
    {
        Test r(0);
        r = num + a.num;
        return r;
    }

    void show()
    {
        cout << "\n num = " << num;
    }
};

int main()
{
    Test t(10);
    Test t1(20);
    Test t2(60);

    Test res(0);
    res = t + t1 + t2;
    res.show();
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Kifayat
  • 1
  • 2
  • Does this answer your question? [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – Richard Critten Nov 07 '19 at 17:29

2 Answers2

4

The problem is that you are accepting an object by non-const reference, not by const reference.

The Test object returned by operator+() is a temporary. A non-const reference can't bind to a temporary.

The reason this was probably working before is the operator+ was executed from left to right - which would look something like this:

object + object + object
temporary + object

The temporary still has the function operator+(), so it can still be called.

On the other hand, when you use parenthesis, it executes like this:

object + object + object
object + temporary

That means that the temporary ends up in a, which, again, can't happen for the reasons stated above.

To fix, either a) turn it into a const reference, or b) pass by value (not recommended because it creates extra copies in memory you don't need):

// a
Test operator +(const Test &a) 
// b
Test operator +(Test a) 

I also highly recommend making this function a const as well:

// a
Test operator +(const Test &a) const
// b
Test operator +(Test a) const

Now you can add const objects even if they are on the right hand side as well.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

(t1 + t2) evaluates to an rvalue expression.

But your operator+(&) can only bind to non-const lvalues. On the other hand const & can bind to both lvalues and rvalues, thus operator+(const &) works.

ich.
  • 17
  • 4