tags:

views:

614

answers:

4

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!

+12  A: 

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.

Johannes Schaub - litb
You can't have an array of classes or structs with const references? Or do you mean you cannnot have an array of const references?MSN
MSN
you can have a struct with references very well. just no array of references
Johannes Schaub - litb
the const i put in there only refers to the binding to temporaries: string const
Johannes Schaub - litb
+3  A: 

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:

  • reference can't be null
  • reference can't be uninitialized (must be initialized when it's defined)
  • reference can't be changed to reference a different object
ChrisW
+2  A: 

I'd say that it's just a pointer with a different syntax.

Javier
+3  A: 

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.

Fabio Ceconello