Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some class methods return "*this" (object reference of self)?

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?

like image 660
scarface Avatar asked Apr 12 '16 11:04

scarface


People also ask

What does * this return in C++?

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.

What does it mean to return a reference to an object?

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 () {

How do you return a self object in C++?

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.

Can a reference variable be returned from a method?

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.


2 Answers

This idiom exists to enable chaining of function calls:

int a, b, c;
a = b = c = 0;

This works well for ints, 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.

like image 93
Magnus Hoff Avatar answered Sep 20 '22 05:09

Magnus Hoff


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.

like image 30
George Sovetov Avatar answered Sep 20 '22 05:09

George Sovetov