References behaves similarly, but not entirely like const pointers. A reference is defined by suffixing an ampersand &
to a type name.
int i = 10;
int &refi = i;
Here, refi
is a reference bound to i
.
References abstracts the semantics of pointers, acting like an alias to the underlying object:
refi = 20; // i = 20;
You can also define multiple references in a single definition:
int i = 10, j = 20;
int &refi = i, &refj = j;
// Common pitfall :
// int& refi = i, k = j;
// refi will be of type int&.
// though, k will be of type int, not int&!
References must be initialized correctly at the time of definition, and cannot be modified afterwards. The following piece of codes causes a compile error:
int &i; // error: declaration of reference variable 'i' requires an initializer
You also cannot bind directly a reference to nullptr
, unlike pointers:
int *const ptri = nullptr;
int &refi = nullptr; // error: non-const lvalue reference to type 'int' cannot bind to a temporary of type 'nullptr_t'