Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning *this with an assignment operator

Tags:

c++

I went over making my own copy constructor and it overall makes sense to me. However, on the topic of doing your own assignment operator I need someone to fill in the blank for me.

I pretty much don't get why you are returning *this in all the examples, such as the one below:

Foo & Foo::operator=(const Foo & f)
{

//some logic

return *this;

}

So if I have some statements like:

Foo f;
f.hour = 7;

Foo g;
g = f;

Once the assignment operator runs, it returns a reference to the g object (the *this). So now the question is, won't I now have a statement implicitly like this?:

g = g (g being a reference)

The thing is, before, setting a reference to just an object would have caused the copy constructor to be invoked. In this case, it doesn't even though it fits the signature of the copy constructor.

like image 930
Ilya Avatar asked Dec 17 '22 23:12

Ilya


1 Answers

You want to return *this so you can chain =:

Foo f, g, h;

f = g = h;

This is basically assigning h into g, then assigning g (returned by return *this) into f:

f = (g = h);

Another situation this is sometimes used in is having an assignment in a conditional (considered bad style by many):

if ( (f = 3).isOK() ) {

With the statement g = f; the return is just ignored, like if you did 3 + 4;.

like image 190
Donald Miner Avatar answered Dec 19 '22 14:12

Donald Miner