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.
{"ft_lang_label":"__label__en","ft_lang_prob":0.8616271,"math_prob":0.7486043,"size":764,"snap":"2022-40-2023-06","text_gpt3_token_len":221,"char_repetition_ratio":0.1513158,"word_repetition_ratio":0.0,"special_character_ratio":0.32329842,"punctuation_ratio":0.1626506,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9716995,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-01-28T05:53:44Z\",\"WARC-Record-ID\":\"<urn:uuid:bd8fbdaf-7634-445a-98b1-e415a40f6eb7>\",\"Content-Length\":\"66329\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:bae93005-0aad-4105-9831-d0b75adbf67c>\",\"WARC-Concurrent-To\":\"<urn:uuid:c92b25d9-22b1-454f-b7d8-b69f358d5bdb>\",\"WARC-IP-Address\":\"172.66.42.251\",\"WARC-Target-URI\":\"https://www.daniweb.com/programming/software-development/threads/281046/doubt-in-operator-overloading\",\"WARC-Payload-Digest\":\"sha1:TFZYFQIPRVQIDIPZDFTS47FJ3AHXSN5S\",\"WARC-Block-Digest\":\"sha1:PZYIODA6S26ZT6Z7NW77QSMQC6X3YJAO\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-06/CC-MAIN-2023-06_segments_1674764499524.28_warc_CC-MAIN-20230128054815-20230128084815-00257.warc.gz\"}"}