Initialization of references (C++ only)

The object that you use to initialize a reference must be of the same type as the reference, or it must be of a type that is convertible to the reference type. If you initialize a reference to a constant using an object that requires conversion, a temporary object is created. In the following example, a temporary object of type float is created:
int i;
const float& f = i; // reference to a constant float

When you initialize a reference with an object, you bind that reference to that object.

Attempting to initialize a nonconstant reference with an object that requires a conversion is an error.

Once a reference has been initialized, it cannot be modified to refer to another object. For example:
int num1 = 10;
int num2 = 20;

int &RefOne = num1;          // valid
int &RefOne = num2;          // error, two definitions of RefOne
RefOne = num2;               // assign num2 to num1
int &RefTwo;                 // error, uninitialized reference
int &RefTwo = num2;          // valid

Note that the initialization of a reference is not the same as an assignment to a reference. Initialization operates on the actual reference by initializing the reference with the object it is an alias for. Assignment operates through the reference on the object referred to.

A reference can be declared without an initializer:
  • When it is used in a parameter declaration
  • In the declaration of a return type for a function call
  • In the declaration of class member within its class declaration
  • When the extern specifier is explicitly used
You cannot have references to any of the following:
  • Other references
  • Bit fields
  • Arrays of references
  • Pointers to references

Direct binding

Suppose a reference r of type T is initialized by an expression e of type U.

The reference r is bound directly to e if the following statements are true:
  • Expression e is an lvalue
  • T is the same type as U, or T is a base class of U
  • T has the same, or more, const or volatile qualifiers than U

The reference r is also bound directly to e if e can be implicitly converted to a type such that the previous list of statements is true.