References

Introduction

  • 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.

Example 1

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.

Const references

  • A const reference will not let you change the value it references.

Use of references

  1. 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.
  2. 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

  1. A pointer can be re-assigned any number of times while a reference can not be reassigned after initialization.
  2. A pointer can point to NULL while reference can never point to NULL.
  3. You can't take the address of a reference like you can with pointers.
  4. There's no "reference arithmetics".

Use of references

  • In function parameters and return types to define interfaces.

TODO
http://www-cs-students.stanford.edu/~sjac/c-to-cpp-info/references

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.