Returning Reference

hey Have a look at this program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<iostream>
#include<conio.h>
using namespace std;
class complex
{
  int r,i;
  public:
  complex(int r,int i)
  {
    (*this).r=r;
    (*this).i=i;
  }
  complex()
  {
    r=0;i=0;
  }  
  complex& operator+=(complex c)
  {
     r+=c.r;
     i+=c.i;
     return *this;
  }
  void display()
  {
       cout<<r<<" "<<i<<"\n";
  }   
  
};
int main()
{
    complex c1(3,4),c2(4,5),c3(2,1),c4(10,20);
    (c1+=c2+=c3)=c4;
    c1.display();
    getch();
    return 0;
}
    


In this program in the operator overloading of += the return type is a reference.
My question is that if we simply return an object instead of returning a reference the program output is wrong...
Why is it so???


Output with reference:
10 20


Output without reference:
9 10
(c1+=c2+=c3)=c4;

Ugh. Setting aside that you should never do this crap... here's what's happening:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// when you return a reference.... the returned value IS the left-hand value.
//   ie, when you return *this, the returned value is actually the same object that 'this'
//  points to.
// when you return by value, the returned value is a COPY of 'this'


// with reference:
// (c1+=c2+=c3)=c4;  <- this... expands to this:

c2 += c3;
c1 += c2;
c1 = c4;


// returning by value... it expands to this:

c2 += c3;          __tempcopy = c2;
c1 += __tempcopy;  __tempcopy = c1;
__tempcopy = c4;


As you can see... when you return by value, the final assignment is actually assigning to a temporary copy, and not assigning to c1. Hence the discrepancy.
Last edited on
Topic archived. No new replies allowed.