Reputation: 439
When I do the following:
1. int y = 5;
2. int &a = y;
3. cout << &a << endl; // the address of a is the same address of y
4. cout << a << endl; // this has the value of y, which is 5.
Upvotes: 0
Views: 2021
Reputation: 85
Read this: http://www.tutorialspoint.com/cplusplus/cpp_pointer_operators.htm
Here in line 2, you are declaring that "Address of 'a' is equal to the address of variable 'y' ".In other words, 'y' has another name 'a'.
I think there cannot be two memory locations with same address. It's just that two variables refer to the same address.
Upvotes: 0
Reputation: 960
References are (broadly) just syntactic sugar for pointers, so a is really just a pointer to y wrapped up with automatic dereferencing. (There is slightly more to it than that, but for the sake of discussion we can think of it that way without getting misled about anything.) So when you ask for the address of a, you are really asking for the underlying pointer value, which has been set to be &y.
When you ask for the value of a, it automatically dereferences the pointer, so it is giving you the value which is at &y. Naturally, this value has y's value.
Does this mean that a and y share the same physically memory location?
No, there are two different memory locations. One holds an int value, the other holds a pointer to that int value.
Or are there 2 different memory locations with the same address?
Pretty much, yes. y is not holding a pointer/address value, though; it is actually holding the integer value itself. (Remember that y is stack memory, not a pointer to a heap object.)
When you take the address of a reference, you are not getting back "a pointer to that reference". You will simply get back the address of the referent itself.
Upvotes: 1
Reputation: 75579
In line 2, you are creating a C++ reference, not using the address of operator. The reference causes a
to be roughly equivalent to y
for all uses including taking its address.
Effectively the symbol a
is just another name for y
.
Upvotes: 6