Assignment operator

suggest change

The assignment operator is one of the most important operators because it allows you to change the status of a variable.

If you do not overload the assignment operator for your class/struct, it is automatically generated by the compiler: the automatically-generated assignment operator performs a “memberwise assignment”, i.e. by invoking assignment operators on all members, so that one object is copied to the other, a member at a time. The assignment operator should be overloaded when the simple memberwise assignment is not suitable for your class/struct, for example if you need to perform a deep copy of an object.

Overloading the assignment operator = is easy, but you should follow some simple steps.

  1. Test for self-assignment. This check is important for two reasons:
- a self-assignment is a needless copy, so it does not make sense to perform it;
- the next step will not work in the case of a self-assignment.
  1. Clean the old data. The old data must be replaced with new ones. Now, you can understand the second reason of the previous step: if the content of the object was destroyed, a self-assignment will fail to perform the copy.
  2. Copy all members. If you overload the assignment operator for your class or your struct, it is not automatically generated by the compiler, so you will need to take charge of copying all members from the other object.
  3. Return *this. The operator returns *this by reference, because it allows chaining (i.e. int b = (a = 6) + 4; //b == 10).
//T is some type
T& operator=(const T& other)
{
    //Do something (like copying values)
    return *this;
}

Note: other is passed by const& because the object being copied from should not be changed, and passing a large object by reference avoids a copy. The parameter is const so that operator= doesn’t modify it accidentally.

The assignment operator can only be overloaded in the class/struct, because the left operand of = is always the class/struct itself. Defining it as a non-member function is ill-formed.

When you declare it in the class/struct, the left value is implicitly the class/struct itself, so there is no problem with that.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents