Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ operator overloading: no known conversion from object to reference?

When I try to compile the following (g++ 4.6.3)

class A {};

A& operator*=( A& a, const A& b )
{
  return a;
}

A operator*( const A& a, const A& b )
{
  return A( a ) *= b;
}

int main( int, char*[] )
{
  A a, b;

  a = a*b;

  return 0;
}

I get the error

/tmp/test.cxx: In function ‘A operator*(const A&, const A&)’:
/tmp/test.cxx:14:20: error: no match for ‘operator*=’ in ‘(* & a) *= b’
/tmp/test.cxx:14:20: note: candidate is:
/tmp/test.cxx:6:1: note: A& operator*=(A&, const A&)
/tmp/test.cxx:6:1: note:   no known conversion for argument 1 from ‘A’ to ‘A&’

This puzzles me - how can a conversion from a class to a reference to that class not be known?

Changing the declaration of class A as follows does not have any effect:

class A
{
public:
  A() {}
  A( const A& ) {}
};

Same error.

I would be extremely grateful for hints as to what's going on here.

like image 545
DrGerm Avatar asked Apr 19 '12 20:04

DrGerm


1 Answers

Like Lucian said, you cannot bind a temporary object to a non-const reference. The expectance of the compiler is that the object will cease to exist after the expression so it makes no sense to modify it.

To fix your code, remove the temporary (making the argument const& makes no sense in operator *=):

A operator*(A a, const A& b)
{
    return a *= b;
}
like image 110
Konrad Rudolph Avatar answered Nov 01 '22 17:11

Konrad Rudolph