Can we reassign the reference in C++?
It seems as if I have actually succeeded in reassigning a reference. Is that true?
No, you haven't. You are actually reassigning the value, and you are not rebinding the reference.
In your example, when you do int &ri = i;
, ri
is bound to i
for its lifetime. When you do ri = j;
, you are simply assigning the value of j
to ri
. ri
still remains a reference to i
! And it results in the same outcome as if you had instead written i = j;
If you understand pointers well, then always think of the reference as an analogical interpretation of T* const
where T
is any type.
ri = j; // >>> Is this not reassigning the reference? <<<
No, ri
is still a reference to i
- you can prove this by printing &ri
and &i
and seeing they're the same address.
What you did is modify i
through the reference ri
. Print i
after, and you'll see this.
Also, for comparison, if you create a const int &cri = i;
it won't let you assign to that.
When you assign something to a reference you actually assign the value to the object the reference is bound to. So this:
ri=j;
has the same effect as
i = j;
would have because ri
is bound to i
. So any action on ri
is executed on i
.