i was reading what is difference b/w pointer variable and reference variable in c++ here's. i got a point from that whereas a reference shares the same memory address but also takes up some space on the stack.. what does it mean that it share the same address space.please clear the how reference has been implemented in c++.
2 Answers
That's a somewhat confusingly-worded answer. But it means something rather simple. The part about taking up stack space just means a reference actually takes up memory. Namely, it takes up the same amount of memory that a pointer does (and in every C++ implementation [that I'm aware of] it's implemented by using an actual pointer).
The part about "share the same memory address" really means that a reference is not an independently-addressable value. If you have a pointer to something, you can take the address of that pointer and end up with a pointer to a pointer to something. But if you have a reference to something, you cannot take the address of that reference. Attempting to do so actually takes the address of the thing being referred to. That is what he means by "shares the same memory address".

- 182,031
- 33
- 381
- 347
Roghly speaking, a reference variable is like a pointer variable that does not look like a pointer (i.e. no pointer syntax for accessing the content). That does not have to do anything with Stack or Heap.
int i = 5; // integer on the Stack
int * j = new int (5); // integer on the Heap (accessible through pointer, naturally)
int & iref = i; // reference to integer on the Stack
int & jref = *j; // reference to integer on the Heap
int * ipointer = & i; // pointer to integer on the Stack
int * jpointer = j; // pointer to integer on the Heap

- 13,315
- 4
- 38
- 65