News & UpdatesProgrammingWeb programming StoreMy Projects

C++ Tutorial – 07 – References

References allow a programmer to create a new name for a variable. They provide a simpler, safer and less powerful alternative to pointers.

Creating references

A reference is declared in the same way as a regular variable, except that an ampersand is appended between the data type and the variable name. Furthermore, at the same time as the reference is declared it must be initialized with a variable of the specified type.

int x = 5;
int& r = x; // r is an alias to x
int &s = x; // alternative syntax

Once the reference has been assigned, or seated, it can never be reseated to another variable. The reference has in effect become an alias for the variable and can be used exactly as though it was the original variable.

r = 10; // assigns value to r/x

References and pointers

A reference is similar to a pointer that always points to the same thing. However, while a pointer is a variable that points to another variable, a reference is only an alias and does not have an address of its own.

int* ptr = &x; // ptr assigned address to x

Reference and pointer guideline

Generally, whenever a pointer does not need to be reassigned a reference should be used instead, because a reference is safer than a pointer since it must always refer to a variable. This means that there is no need to check if a reference refers to null, as should be done with pointers. It is possible for a reference to be invalid – for example when a reference refers to a null pointer – but it is much easier to avoid this kind of mistake with references than it is with pointers.

int* ptr = 0; // null pointer
int& ref = *ptr;
ref = 10; // segmentation fault (invalid memory access)
Recommended additional reading:
Sams - Teach Yourself C++ in One Hour a Day