const reference return
Sep 6, 2015 at 10:00am UTC
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!!
Sep 6, 2015 at 10:33am UTC
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)
Sep 13, 2015 at 8:34am UTC
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 Sep 13, 2015 at 11:38am UTC
Sep 13, 2015 at 1:58pm UTC
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
Sep 20, 2015 at 2:49pm UTC
Ok MiiNiPaa! Now I got it!! Thank you very much for your help!
Topic archived. No new replies allowed.