If I have this:
int a = 2; int b = 4; int &ref = a;
How can I make ref
refer to b
after this code?
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.
Once a reference is established to a variable, you cannot change the reference to reference another variable. To get the value pointed to by a pointer, you need to use the dereferencing operator * (e.g., if pNumber is a int pointer, *pNumber returns the value pointed to by pNumber .
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.
To assign reference to a variable, use the ref keyword. A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. Declare the reference parameters using the ref keyword.
This is not possible, and that's by design. References cannot be rebound.
With C++11 there is the new(ish) std::reference_wrapper.
#include <functional> int main() { int a = 2; int b = 4; auto ref = std::ref(a); //std::reference_wrapper<int> ref = std::ref(a); <- Or with the type specified ref = std::ref(b); }
This is also useful for storing references in containers.
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