Reputation: 1223
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.
Upvotes: 4
Views: 455
Reputation: 12481
The reason is so that the result of your assignment can be an rvalue in another expression.
Upvotes: 0
Reputation: 10074
I think you're confusing the idea of infix notation a bit. g = f
does not mean call operator= of g with f and put the result into g
it means apply operator= on g with parameter f and set the value of this expression to the result
. This is identical behavior to the other infix operators such as +
or /
.
Operators in some languages can be applied like a normal function (and in C++ with some extraneous syntax) such as = (g f)
which shows the concept a bit more clearly.
Edit:
For example, what is often used as an example for IO:
// loop until some sentinel value
while ((nextChar = (char) getchar()) != 'Q') {
string += nextChar;
}
Notice that because the =
operator returns its first argument (nextChar in this example) you can compose the assignment and testing.
Upvotes: 4
Reputation: 10060
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)
No, but self assignment is something you need to check for. What returning *this
does is make the value of the expression (g=f)
, g
. Which is useful for chaining assignments. In a statement like
Foo a, b, c;
a = b = c;
a
is being assigned the return value from the method operator=
. Returning *this makes this statement do what is expected (the value of c is assigned to b, then the new value of b is assigned to a).
Upvotes: 0
Reputation: 39913
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;
.
Upvotes: 8