3

Consider the following operator overloading scenario

class integer
{
   public:
   int a;
   integer()
   {
        a = 0;
   }
  friend integer operator+(integer &a ,int b);
};
integer operator+(integer &a,int b)
{
    a.a = a.a + b;
    return a;
}
int main()
{
   integer obj;
   integer obj2;
   obj+2; //Line 1.  this works.

The operator+ function returns an object of integer type.So why can't i execute a function call like

(obj+2)+3; //no match for 'operator+' (operand types are 'integer' and 'int')

While this works

obj2 = obj+2;
obj2+3;
3
  • 3
    (obj+2) returns a temporary. Temporaries can't bind to a non-const reference. Commented Apr 14, 2016 at 5:08
  • 8
    Taking a step back, you've named your operator +, but it behaves like +=. This will end in tears. Commented Apr 14, 2016 at 5:09
  • Simply making operator+ take a const integer & a and making it not modify the reference, but modify a new integer that you return will make this work as you want, and as it should with regards to what @IgorTandetnik said. Commented Apr 14, 2016 at 6:09

2 Answers 2

3

integer &a means that a can only refer to an lvalue. But obj+2 is not an lvalue.

To fix this, you should change your parameter to integer a, which:

  • can bind to rvalues
  • makes your function actually perform operator+'s function.

If your first parameter is integer& it would suggest you are trying to write operator+=. For that function, the solution would be to also return integer&, so that obj+=2 is an lvalue.

Sign up to request clarification or add additional context in comments.

Comments

2

As a corollary to M.M's answer (which you should accept), here is the fixed code:

class integer
{
   public:
   int a;
   integer()
   {
        a = 0;
   }
  friend integer operator+(integer a ,int b);
};

// fix: arg 1 passed by value
integer operator+(integer a,int b)
{
    a.a = a.a + b;
    return a;
}

int main()
{
   integer obj;
   integer obj2;
   obj+2;
  (obj+2)+3;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.