user36064
user36064

Reputation: 873

What value does a Reference Variable in C++ store?

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

Answers (4)

Fabio Ceconello
Fabio Ceconello

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

Johannes Schaub - litb
Johannes Schaub - litb

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

Javier
Javier

Reputation: 62583

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

Upvotes: 2

ChrisW
ChrisW

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:

  • 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

Upvotes: 3

Related Questions