Hello people I have a small doubt in operator overloading
I am trying to overload the assignment operator. Here is my code for that
class rational
{
int x;
int y;
public:
//All the constructos
rational operator= (rational num)
{
// Why do we need to return a reference
this->x= num.x;
this->y= num.y;
return *this;
}
};
ostream& operator<<(ostream& out, rational num)
{
out<<"X is "<<num.x<<" Y is "<<num.y<<endl;
return out;
}
int main()
{
rational r1,r2,r3,r4(10,20);
r1=r2=r3=r4;
cout<<"r1 is "<<r1;
cout<<"r2 is "<<r2;
cout<<"r3 is "<<r3;
cout<<"r4 is "<<r4;
}
I have seen this example in various websites and in all of those the assignment operator returns a reference of the object instead of just the object the object. What exactly is the reason for that ?