References (C++ only)

A reference is an alias or an alternative name for an object or function. All operations applied to an object reference act on the object to which the reference refers. The address of a reference is the address of the aliased object or function.

An lvalue reference type is defined by placing the reference modifier & or bitand after the type specifier. C++11An rvalue reference type is defined by placing the reference modifier && or and after the type specifier. For the details of rvalue references, see Using rvalue references (C++11).C++11 Reference types include both lvalue reference C++11and rvalue referenceC++11 types.

Because arguments of a function are passed by value, a function call does not modify the actual values of the arguments. If a function needs to modify the actual value of an argument or needs to return more than one value, the argument must be passed by reference (as opposed to being passed by value). Passing arguments by reference can be done using either references or pointers. Unlike C, C++ does not force you to use pointers if you want to pass arguments by reference. The syntax of using a reference is simpler than that of using a pointer. Passing an object by reference enables the function to change the object being referred to without creating a copy of the object within the scope of the function. Only the address of the actual original object is put on the stack, not the entire object.

For example:
int f(int&);
int main()
{
      extern int i;
      f(i);
}

You cannot tell from the function call f(i) that the argument is being passed by reference.

The following types of references are invalid:
  • References to NULL
  • References to void
  • References to invalid objects or functions
  • References to bit fields
  • References to references C++11except with reference collapsing. See Reference collapsing (C++11) for more information.C++11
You also cannot declare arrays of references, pointers to references, and cv-qualifiers on references. If cv-qualifiers are introduced through a typedef or template argument deduction, the cv-qualifiers are ignored.

For information on references to functions, see Pointers to functions.