References

suggest change

Basics of references

A reference is an alias for an existing object or function. An lvalue-reference type is written with an ampersand (&) after the referred-to type.

int i = 10;
int &refi = i;

Here, refi is a reference bound to i.

Operations on the reference operate on the referred-to 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 when they are defined. A reference cannot later be rebound to another object; assignment through it modifies the object to which it is already bound. The following declaration is ill-formed:

int &i; // error: declaration of reference variable 'i' requires an initializer

Unlike a pointer, a reference cannot be initialized with nullptr:

int *const ptri = nullptr;
int &refi = nullptr; // error: non-const lvalue reference to type 'int' cannot bind to a temporary of type 'nullptr_t'

A reference aliases an existing object

A reference provides another name for an object. Taking the address of a reference therefore produces the address of the referred-to object. The language does not require a reference to occupy storage, although an implementation may use storage for it when necessary.

#include <iostream>

int main() {
    int i = 10;
    int& j = i;
    
    std::cout << &i << '\n';
    std::cout << &j << '\n';
}

Both output statements print the same address. Passing an object by reference likewise gives the function an alias to the original object:

#include <iostream>

void print_address(int& parameter) {
    std::cout << "Address inside function: " << &parameter << '\n';
}

int main() {
    int i = 10;
    std::cout << "Address inside main: " << &i << '\n';
    print_address(i);
}

Again, both lines print the same address. Because an lvalue reference must be bound to an object, a declaration without an initializer is ill-formed:

int &i;

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents