course content

Course Content

Introduction to C++

ReferenceReference

A reference is another way to access data stored in a variable. The reference is declared with the now familiar ampersand (&), for example:

The main difference between a reference and a pointer is that the reference must always be initialized, there cannot be empty references. Such a reference declaration is invalid, and you will get a compilation error:

A reference allows you to access data directly, just like pointers. When accessing the link, we get the data already "unpacked" from the address:

cpp

main.cpp

To make sure that the reference points to the variable, use the reference operator &:

cpp

main.cpp

A reference is the same pointer implicitly dereferenced when accessing the value it points to. All the manipulations we applied to the pointer can be applied to references.

Note

References "under the hood" are implemented using pointers.

Section 6.

Chapter 6