Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ compile error - no match for ‘operator=’

The following code compiles without problem

class MyClass
{
public:
  MyClass() { std::cout << "Default Constructor!" << std::endl; }
  MyClass& operator=(const MyClass& m) { std::cout << "Copy assignment operator!" << std::endl; }
};

int main()
{
  MyClass a;
  MyClass d;
  d = MyClass(a);
}

but when I change assignment operator argument to be non-const compiler prints error:

MyClass& operator=(MyClass& m) { std::cout << "Copy assignment operator!" << std::endl; }

error: no match for ‘operator=’ (operand types are ‘MyClass’ and ‘MyClass’)

I want to know the reason. Thanks in advance.

like image 356
Ashot Khachatryan Avatar asked Mar 18 '23 03:03

Ashot Khachatryan


1 Answers

Because the MyClass& makes your operator= without const not a proper assignment operator. It must be operator=(const MyClass&) (or operator=(MyClass) but don't do that unless you know what you are doing, copy-&-swap...).

Otherwise, your code d = MyClass(a) cannot compile because a non-const reference will not bind to a temporary (r-value) such as MyClass(a).

Note that, even without the const, a code such as d = a will compile, because the a is not an r-value. However, it is still not a proper assignment operator.

like image 143
rodrigo Avatar answered Mar 31 '23 23:03

rodrigo