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
No,
riis still a reference toi– you can prove this by printing&riand&iand seeing they’re the same address.What you did is modify
ithrough the referenceri. Printiafter, and you’ll see this.Also, for comparison, if you create a
const int &cri = i;it won’t let you assign to that.