Look at the following code:
#include <iostream>
using namespace std;
class Widet{
public:
Widet(int val = 0):value(val)
{
}
Widet& operator=(Widet &rhs)
{
value = rhs.value;
return *this;
}
int getValue()
{
return value;
}
private:
int value;
};
int main()
{
Widet obj1(1);
Widet obj2(2);
Widet obj3(0);
(obj3 = obj2) = obj1;
cout << "obj3 = " << obj3.getValue() << endl;
}
The code runs successfully and the output is (using VS2008):

When I let the operator= return a value instead of reference:
Widet operator=(Widet &rhs)
{
value = rhs.value;
return *this;
}
It also runs successfully and the output is :

My question is :Why the second code runs well?Should not we get a error?
Why it is a good habit to return reference to *this instead of *this?
Because it’s perfectly valid code. It returns a temporary copy of the object, and you’re allowed to call member functions (including
operator=()) on temporary objects, so there is no error.You would get an error if the object were uncopyable.
Because not all objects are copyable, and some objects are expensive to copy. You can take a reference to any object, and references are always cheap to pass around.