According to this question you can\'t change what a reference refers to. Likewise the C++ Primer 5th Edition states
Once we have defined a reference,
You are not reassigning a reference. A reference acts as an alias for a variable. In this case, ref
is an alias for a
, so
ref = b;
is the equivalent of
a = b;
You can easily check that by printing out the value of a
:
std::cout << a << std::endl; // prints 4
You can understand how references work by comparing their behavior to that of a pointer. A pointer can be thought of as the name of the address of a variable; however a reference is just the name of the variable itself--it is an alias. An alias, once set, can never be changed whereas you can assign a pointer a new address if you want. So you have:
int main(void)
{
int a = 2;
int b = 4;
int* ptr_a = &a;
int& ref_a = a;
ptr_a = &b; //Ok, assign ptr_a a new address
ref_a = &b; //Error--invalid conversion. References are not addresses.
&ref_a = &b; //Error--the result of the `&` operator is not an R-value, i.e. you can't assign to it.
return 0;
}