Today we're going to explain references—a topic which might not seem like a logical continuation of our object-oriented programming tutorial—but that is actually very important to understand. References are a data type in the C++ language which have similarities with the pointer type inherited from C. (You can learn about pointers in one of our articles from the Basics of Programming series: Pointers.)
In C++, a reference is a simple datatype that is less powerful but safer than the pointer type. A reference, like a pointer, stores the address of an object that is located elsewhere in memory—we say that it is an "address type".
References are declared like this:
type &referenceToX = x; //reference type
is any of the data types we've learned, or an object of some class.
int x = 0;
int &ref = x; //or int& ref = x -- equivallent notations
x = 5; //ref=5
A reference variable is an alias, meaning it's another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.
Let's analyze the differences between pointers and references:
- References cannot be null, and pointers can; every reference refers to some object, although it may or may not be valid.
- Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time.
- A reference must be initialized when it is created. Pointers can be initialized at any time.
References are often used in C++, which will be obvious when we start working with operator and method overloading.
Here are two situations in which one would use references:
- passing parameters by address (instead of by value)
- using a reference as an lvalue
Sometimes, we want to pass arguments to the function by address. This happens, for example, when we want our function to modify that exact variable or object, instead of making a local copy of the argument on the stack and modifying that value. In C++, references are used for this instead of pointers, because they are considered safer since they cannot be null.
Another reason for using references is that they are "l-values": briefly, an lvalue (locator value) represents an object that occupies some identifiable location in memory (i.e. has an address). This makes it possible to assign a value to the result of a function call—provided that the function's return type was a reference.
Also, references are crucial in writing copy constructors, which will be covered in one of the next articles.