'c++ return *this, how to think it
When I searched for return *this, I found someone explaining it as a chained assignment function.

But when I follow the blogger's implementation, I found that this is not the case.


Though one has the code return *this, the other has not, the two results is same.
#include <iostream>
using namespace std;
class Wd {
private:
public:
int a;
int b;
Wd &operator=(Wd const &as) {
this->a = as.a;
this->b = as.b;
return *this;
};
};
int main() {
Wd a;
a.b =3;
a.a =4;
Wd c,b,d;
d.a=6;
d=c=b=a;
cout<<d.a<<a.a<<b.a<<c.a<<endl;
return 0;
}
Solution 1:[1]
Semantic of assignment expression like a=b is :
- first, set the value of
ato the value ofb, - second, the value of the whole expression is the value of
aafter assignment.a=b=cis equivalent toa = (b=c).
As a=b is a.operator=(b), the return value of the operator must be the value of a after assignment, thus the following is the most common way of implementing it:
K &operator=(const K &arg) {
// code to assign this with values in arg
return *this; // return the current assigned object
}
Solution 2:[2]
So this
class Wd{
public:
int a;
int b;
Wd &operator =(Wd const &as){
this->a = as.a;
this->b = as.b;
return *this;
};
};
creates an object with only one function operator=.
That function is defined as returning a reference to the invoking object.
return *this;
says 'return what the this object points at'. this points at the current Wd instance. If the retrun type we Wd then it would retunr a copy, but becuase the return type is Wd& it returns a reference to it, this is effectively a pointer
so now look at the main code
Wd a;
a.b =3;
a.a =4;
first we create a Wd and initialize its members.
Then we do (simplified a bit)
Wd c;
Wd d;
d = c = a;
d = c= a translates to
d.operator=(c.operator=(a))
and because c.operator=(a) returns a reference to a this is equivalent to
d.operator=(a)
One of the main reason for the existance of references is to permit chaining like this. The most well known one is this
cout << x << " " << y << "!!" << z;
this works because operator<< for streams is defined as returning a reference to its invoking stream.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jean-Baptiste Yunès |
| Solution 2 | pm100 |
