C++ Assignment operator


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 assigment operator for your class/struct, it is automatically generated by the compiler: the automatically-generated assignment operator performs a "memberwise assignment", ie by invoking assignment operators on all members, so that one object is copied to the other, a member at 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.
  2. 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.
  3. Copy all members. If you overload the assigment 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.
  4. Return *this. The operator returns by itself 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 assigned should not be changed, and passing by reference is faster than by value, and to make sure than operator= doesn't modify it accidentally, it is const.

The assignment operator can only to be overloaded in the class/struct, because the left value of = is always the class/struct itself. Defining it as a free function doesn't have this guarantee, and is disallowed because of that.

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