Why should the assignment operator return a reference to the object?
The usual form returns a reference to the target object to allow assignment chaining. Otherwise, it wouldn't be possible to do:
Foo a, b, c;
// ...
a = b = c;
Still, keep in mind that getting right the assigment operator is tougher than it might seem.
The return type doesn't matter when you're just performing a single assignment in a statement like this:
x = y;
It starts to matter when you do this:
if ((x = y)) {
... and really matters when you do this:
x = y = z;
That's why you return the current object: to allow chaining assignments with the correct associativity. It's a good general practice.
Your assignment operator should always do these three things:
Take a const-reference input
(const MyClass &rhs)
as the right hand side of the assignment. The reason for this should be obvious, since we don't want to accidentally change that value; we only want to change what's on the left hand side.Always return a reference to the newly altered left hand side,
return *this
. This is to allow operator chaining, e.g.a = b = c;
.-
Always check for self assignment
(this == &rhs)
. This is especially important when your class does its own memory allocation.MyClass& MyClass::operator=(const MyClass &rhs) { // Check for self-assignment! if (this == &rhs) // Same object? return *this; // Yes, so skip assignment, and just return *this. ... // Deallocate, allocate new space, copy values, etc... return *this; //Return self }