I have read in many places about references:
Reference is like a const pointer
Reference always refer to an object
Once initialised, a Reference cannot be reseated
I want to make myself clear on the last point. What does that mean?
I tried this code:
#include <iostream>
int main()
{
int x = 5;
int y = 8;
int &rx = x;
std::cout<<rx<<"\n";
rx = y; //Changing the reference rx to become alias of y
std::cout<<rx<<"\n";
}
Output
5
8
Then what does it mean by "References cannot be reseated"?
A pointer in C++ is a variable that holds the memory address of another variable. A reference is an alias for an already existing variable. Once a reference is initialized to a variable, it cannot be changed to refer to another variable. Hence, a reference is similar to a const pointer.
The grammar doesn't allow you to declare a “const reference” because a reference is inherently const . Once you bind a reference to refer to an object, you cannot bind it to refer to a different object.
References to pointers can be declared in much the same way as references to objects. A reference to a pointer is a modifiable value that's used like a normal pointer.
Constant pointers: In constant pointers, the pointer points to a fixed memory location, and the value at that location can be changed because it is a variable, but the pointer will always point to the same location because it is made constant here.
This line:
rx = y;
Does not make rx point to y. It makes the value of x (via the reference) become the value of y. See:
#include <iostream>
int main()
{
int x = 5;
int y = 8;
int &rx = x;
std::cout << rx <<"\n";
// Updating the variable referenced by rx (x) to equal y
rx = y;
std::cout << rx <<"\n";
std::cout << x << "\n";
std::cout << y << "\n";
}
Thus it is not possible to change what rx refers to after its initial assignment, but you can change the value of the thing being referenced.
A reference is therefore similar to a constant pointer (where the pointer address is the constant, not the value at that address) for the purposes of this example. However there are important differences, one good example (as pointed out by Damon) being that you can assign temporaries to local const references and the compiler will extend their lifetime to persist for the lifetime of the reference.
Considerable further detail on the differences between references and const pointers can be found in the answers to this SO post.
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