Assignment Operator (C++)

Assignment Operator (C++)

In the C++ programming language, the assignment operator, '=', is the operator used for assignment. Like most other operators in C++, it can be overloaded.

The copy assignment operator, often just called the "assignment operator", is a special case of assignment operator where the source (right-hand side) and destination (left-hand side) are of the same class type. It is one of the special member functions, which means that a default version of it is generated automatically by the compiler if the programmer does not declare one. The default version performs a memberwise copy, where each member is copied by its own copy assignment operator (which may also be programmer-declared or compiler-generated).

The copy assignment operator differs from the copy constructor in that it must clean up the data members of the assignment's target (and correctly handle self-assignment) whereas the copy constructor assigns values to uninitialized data members. For example:

My_Array first; // initialization by default constructor My_Array second(first); // initialization by copy constructor My_Array third = first; // Also initialization by copy constructor second = third; // assignment by copy assignment operator

Another difference that effect the implementation is that assignment operators have a return value. Returning a reference to the object allows assignment operators to be chained, for example:

a = b = c;

Support for this behavior is not required by the C++ language, but is standard. For example, the containers of the standard C++ library require this return value.

Read more about Assignment Operator (C++):  Overloading Copy Assignment Operator