I have read everywhere that a reference has to be initialized then and there and can't be re-initialized again.
To test my understanding, I have written the following small program. It seems as if I have actually succeeded in reassigning a reference. Can someone explain to me what is actually going on in my program?
#include <iostream>
#include <stdio.h>
#include <conio.h>
using namespace std;
int main()
{
int i = 5, j = 9;
int &ri = i;
cout << " ri is : " << ri <<"\n";
i = 10;
cout << " ri is : " << ri << "\n";
ri = j; // >>> Is this not reassigning the reference? <<<
cout << " ri is : " << ri <<"\n";
getch();
return 0;
}
The code compiles fine and the output is as I expect:
ri is : 5
ri is : 10
ri is : 9
Remember, once you initialize a reference, you cannot reassign it. A reference practically stands for an object. You cannot make it 'point' to a different object.
Formally speaking, that is impossible as it is forbidden by design. Arbitrarily speaking, that is possible. A references is stored as a pointer, so you can always change where it points to as long as you know how to get its address.
I have read about C++ reference type variables as they cannot be reinitialized or reassigned, since they are stored 'internally' as constant pointers. So a compiler would give a error.
Once a reference is established to a variable, we cannot change the reference to reference another variable.
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.
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.
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
.
You are not reassigning the reference when executing ri = j;
. You're actually assigning j
to i
. Try printing i
after the line and you'll see that i
changed value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With