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 and destination 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.
The copy assignment operator differs from the copy constructor in that it must clean up the data members of the assignment's target whereas the copy constructor assigns values to uninitialized data members. For example:

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

Return value of overloaded assignment operator

The language permits an overloaded assignment operator to have an arbitrary return type. However, the operator is usually defined to return a reference to the assignee. This is consistent with the behavior of assignment operator for built-in types and allows for using the operator invocation as an expression, for instance in control statements or in chained assignment. Also, the C++ Standard Library requires this behavior for some user-supplied types.

Overloading copy assignment operator

When deep copies of objects have to be made, exception safety should be taken into consideration. One way to achieve this when resource deallocation never fails is:
  1. Acquire new resources
  2. Release old resources
  3. Assign the new resources' handles to the object

class My_Array;

However, if a no-fail swap function is available for all the member subobjects and the class provides a copy constructor and destructor, the most straightforward way to implement copy assignment is as follows:

public:
void swap // the swap member function

My_Array & operator = // note: argument passed by value!

Assignment between different classes

C++ supports assignment between different classes, both via implicit copy constructor and assignment operator, if the destination instance class is the ancestor of the source instance class:

class Ancestor ;
class Descendant : public Ancestor ;
int main

Copying from ancestor to descendant objects, which could leave descendant's fields uninitialized, is not permitted.