Start New Discussion within our Software Development Community

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 ?

>>// Why do we need to return a reference
That isn't returning a reference, but a complete duplicate copy of the class. If you want it to return a reference then you need to change it like this: rational& operator= (rational num)

This question has already been answered. Start a new discussion instead.