- References are a type of C++ variable that act as an alias to another variable.
- A reference is defined by preceding a variable name by the & symbol.
int ival = 1024; int &refVal = ival; // ok: refVal refers to ival int &refVal2; // error: a reference must be initialized int &refVal3 = 10; // error: initializer must be an object
All operations on a reference are actually operations on the underlying object to which the reference is bound.
int nValue = 5; int nValue2 = 6; int &rnRef = nValue; rnRef = nValue2; // assigns value 6 to nValue -- does NOT change the reference.
- A const reference will not let you change the value it references.
Use of references
- Const references are used as function parameters. Because const references allow us to access but not change the value of an object, they can be used to give a function access to an object, but give assurance to the caller that the function will not change the object.
- easier access to nested data.
References and pointers
- A reference acts like a const pointer that is implicitly dereferenced.
Example: *pnValue and rnValue evaluate identically.
int nValue = 5; int *const pnValue = &nValue; int &rnValue = nValue;
- References always point to valid objects and can never be pointed to deallocated memory, so references are safer to use than pointers.
- Pointers should be used in situations where references are not sufficient such as dynamically allocating memory.
Differences between references and pointers
- A pointer can be re-assigned any number of times while a reference can not be reassigned after initialization.
- A pointer can point to NULL while reference can never point to NULL.
- You can't take the address of a reference like you can with pointers.
- There's no "reference arithmetics".
Use of references
- In function parameters and return types to define interfaces.