Question

Possible Duplicate:
behaviour of the implicit copy constructor / assignment operator
C++ - conditions for automatic generation of default ctor, copy ctor,and default assignment operator?

Is it true that the overloaded assignment operator is always provided by the C++ compiler? What are the cases in which it is not provided by the c++ compiler?

Was it helpful?

Solution

An Assignment/Copy Assignment(=) operator is provided by any C++ compiler implicitly unless you have const or reference members in your class.

In case of const member compiler cannot provide = because that would break the contract of not modifying const member after initialization.

In case of reference member compiler does not provide = because it leaves it to the user of the class to decide the appropriate behavior.

OTHER TIPS

Is it true that the overloaded assignment operator is always provided by the C++ compiler.

If you don't declare your own assignment operator, the compiler will implicitly declare one for you (always). If you use it, then the compiler will also implicitly define it (always).

There is a common misunderstanding shown in Als's answer that it will not be defined under some conditions. That is wrong, whether the type has constant members or references does not matter at all, the compiler will declare and define it. The situation for those cases is that the implicitly defined compiler will fail to compile.

If you try that in a compiler, the error will not point to a missing assignment operator, but rather to an error while compiling the implicitly defined assignment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top