const reference return

Hi there!!

I am just wondering what is the difference between returning a non-const object and a const reference.

For example, this code outputs the same result regardless of the return type in the assignment operator.

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

class Test
{
public:
  int *ptr;

  Test(int i = 0)
  {
    ptr = new int(i);
  }

  const Test& operator=(const Test &t)
  {
    *ptr = *(t.ptr);
    return *this;
  }
  
  //this produces the same result, why?
//  Test operator=(const Test &t)
//  {
//    *ptr = *(t.ptr);
//    return *this;
//  }
};

int main()
{

  Test t1(5);
  Test t2;
  t2 = t1;
  t1.ptr = new int(10);
  cout << "t2 = " << *(t2.ptr) << endl;

  return 0;
}


Could someone explain to me the differences? Thank you so much!!
Value returning introduces a copy. That means each time you assigne you class another copy is made which is going to be immideately destroyed.

Historically operator= returns const reference so this would be possbile:
1
2
a = b = c = d; //Assign a, b and c value of d — three objects changed, no copies
 
With value-returning operator= you will have 3 changed object and 3 immideately destroyed copies.

Another use for non-void operator= (taken from C) while((c = getchar()) != EOF)
Hi MiiNiPaa,

Thank you very much for your response!

As you said, value returning introduces a copy. But if a reference is returned, it means the object itself is returned, in this case the 't1' object.

So t1 and t2 are the same object, aren't they? But when I change a pointer variable of t1 (t1.ptr), it does not change in t2. Why?

1
2
3
t2 = t1;
t1.ptr = new int(10);//t1 and t2 are the same object
cout << "t2 = " << *(t2.ptr) << endl;//but t2.ptr is still 5 
Last edited on
So t1 and t2 are the same object
No. Operator= changes object t2 to have same data as t1, but it does not make it same object ( they have diferent addresses, for example) and then returns a reference to t2 object
Ok MiiNiPaa! Now I got it!! Thank you very much for your help!
Topic archived. No new replies allowed.