References & Pointers

About The examples given in the lecture about References & Pointers. I understand that a pointer, even when it points to the memory address of another variable, it’s still variable which can be located in memory. If we perform something like the following:

int val1=2;
int *MyPointer=val1;
std::cout << "Pointer Address in memory: " << &MyPointer << std::endl;

with that, we would be printing out the location in memory of the pointer.

My question is what happens with the References, are those variables?
If I wanted to know the location in memory of a defined reference, how would I printed it to the console since doing the following only gets me the address of the variable being referenced:

int val1=2;
int &MyReference=val1;
std::cout << "Reference Address in memory???: " << &MyReference << std::endl;

If someone could clear this out for me I would really appreciate it.

See the following:

https://isocpp.org/wiki/faq/references#reseating-refs

…Unlike a pointer, once a reference is bound to an object, it can not be “reseated” to another object. The reference itself isn’t an object (it has no identity; taking the address of a reference gives you the address of the referent; remember: the reference is its referent).

…whereas a reference shares the same memory address (with the original variable) but also takes up some space on the stack. Since a reference has the same address as the original variable itself, it is safe to think of a reference as another name for the same variable.

Great, thanks for your explanation and the references! Now it’s clear :smile:

Didn’t actually explain anything myself but thanks :stuck_out_tongue:

Privacy & Terms