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?