References

References#

reading

C++ references from Wikipedia

References in C++ provide access to an object indirectly. It essentially becomes another name for the object and allows you to read and write to its memory directly.

We use the & operator to create a reference.

A great use of references is to access and modify data in containers (like strings, vectors, and arrays) via a ranged-for loop. We’ll see this next.

Basic example#

Here’s a simple example:

Listing 40 simple_reference.cpp#
#include <iostream>

int main() {

    int x{10};
    int &x_ref = x;

    x_ref++;

    std::cout << "x is now " << x << std::endl;

}

Since x_ref is a reference for x, modifying its value directly modifies x ‘s value as well.

Note

You can define the reference as:

int& x;

or

int &x;

Important

A reference must be initialized when it is created. You cannot do:

double x{3.14};
double &x_ref;

x_ref = x;

const reference#

We can create a const reference that provides only read access to an object:

int a = 1.0
const int& a_ref = a;

Now if we try to update a through a_ref, we’ll get a compile-time error:

Listing 41 const_reference_example.cpp#
#include <iostream>

int main() {

    int i{2};
    const int& i_ref = i;

    i_ref++;

}

const references will be very useful when we start writing functions and wish to pass objects in a read-only.

Note

You cannot make a reference to a reference.