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)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.