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.
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.*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.