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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With