There are plenty of codes for explanation on the internet (also specifically here, on stackoverflow) that return *this
.
For example from post Copy constructor and = operator overload in C++: is a common function possible? :
MyClass& MyClass::operator=(const MyClass& other)
{
MyClass tmp(other);
swap(tmp);
return *this;
}
When I write swap as:
void MyClass::swap( MyClass &tmp )
{
// some code modifying *this i.e. copying some array of tmp into array of *this
}
Isn't enough setting return value of operator =
to void
and avoid returning *this
?
this means pointer to the object, so *this is an object. So you are returning an object ie, *this returns a reference to the object. Save this answer.
It means you return by reference, which is, at least in this case, probably not desired. It basically means the returned value is an alias to whatever you returned from the function. Unless it's a persistent object it's illegal. For example: int& foo () {
If you want to return the same object, you can use a special pointer called this. As its name implies, the this pointer is a self referencing object, which means it allows you to designate the object that is making the call as the same object you are referring to.
A C++ function can return a reference in a similar way as it returns a pointer. When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var. But you can always return a reference on a static variable.
This idiom exists to enable chaining of function calls:
int a, b, c;
a = b = c = 0;
This works well for int
s, so there's no point in making it not work for user defined types :)
Similarly for stream operators:
std::cout << "Hello, " << name << std::endl;
works the same as
std::cout << "Hello, ";
std::cout << name;
std::cout << std::endl;
Due to the return *this
idiom, it is possible to chain like the first example.
One of reasons why *this
is returned to allow assignment chains like a = b = c;
which is equivalent to b = c; a = b;
. In general, result of assignment could be used anywhere, e.g. when invoking functions (f(a = b)
) or in expressions (a = (b = c * 5) * 10
). Although, in most cases, it just makes code more complicated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With