0
Rational  operator = ( const Rational & rhs);
Rational & operator = ( const Rational & rhs);

this two line of code work the same when compiling. However, every material of C++ uses the second one (the one with ref) when overloading the assignment operator. I also tried these statement

    rational r1(2, 3);
    rational r2(22, 7);
    rational r3;
    (r3 = r2) = r1;
    r3 = r2 = r1;

for the line

    r3 = r2 = r1;

the output is the same

for the line

    (r3 = r2) = r1;

the output for the one without ref

    2/3
    22/7
    22/7

the output for the one with ref

   2/3
   22/7
   2/3  

why is this behavior happening ? which one should be used?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • Without returning a reference, the result of `(r3 = r2)` is a temporary object that will be destructed as soon as the full expression is finished. Any assignments to that temporary object will be lost immediately. – Some programmer dude Mar 12 '23 at 12:10

0 Answers0