[ fromfile: references.xml id: references ]
In essence, an lvalue is anything with a memory address that can be given a name.
In C++, a reference provides a mechanism for assigning an alternative name to an lvalue.
For example:
int n; int& rn = n;
The ampersand &
following the int
indicates that rn
is an
int
reference.
For its entire life, a reference variable will be an alias for the actual lvalue that initialized it.
This association cannot be revoked or transferred.
For example:
int a = 10, b = 20; int& ra = a; // ra is an alias for a ra = b; // this causes a to be assigned the value 20 const int c = 45; // c is a constant: its value is read-only. const int& rc = c; // legal but probably not very useful. rc = 10; // compiler error - const data may not be changed.
The address-of operator applies to an object and returns its address. Hence, it appears only on the right side of an assignment or in an initializing expression for a pointer variable.
In connection with references, the ampersand is used only in the declaration of a reference. Hence, it appears only between the type name and the reference name as it is declared.
Note | |
---|---|
For reference declarations, we recommend placing the ampersand immediately to the right of the type name: Type& ref(initLval);
|
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |