Reputation: 873
A pointer stores/is assigned a memory address;
what about a reference variable?
it stores the actual value of an object just like any other non-pointer simple variables on Stack?
Thanks!
Upvotes: 4
Views: 3455
Reputation: 16039
Internally, it's just a pointer to the object (although the standard not necessarily mandates it, all compilers implement this way). Externally, it behaves like the object itself. Think of it as a pointer with an implicit '*' operator wherever it is used (except, of course, the declaration). It's also a const-pointer (not to be confused with a pointer-to-const), since it cannot be redirected once declared.
Upvotes: 4
Reputation: 506905
A reference does contain nothing in itself. The C++ Standard even states that an implementation is not required to allocate any storage for a reference. It's really just an alias for the object or function that it references. Trying to take the value of a reference will take the value of the object or function (in that case, you get a function pointer, just like when you would try to get the value out of the function using its original name) it references, instead.
Of course, when you go on lower levels and look at the assembler code, references are just like pointers. But at the language level, they are completely different beasts. References to const, for example, can bind to temporaries, they are required to implement a copy constructor, for overloading operators and they can't be put into an array (not even if you initialize all elements of it), because references are no objects (as opposed to pointers). They are, as trivial as it may sound, reference types.
Upvotes: 15
Reputation: 56113
it stores the actual value of an object just like any other non-pointer simple variables on Stack?
Not exactly: because you don't have two copies of the value (one copy in the object, and another copy in the reference to the object); instead, the reference is probably implemented as a pointer to the object.
Differences between a pointer and an object:
Upvotes: 3