C++ – References

I learned about references at the end of Lesson 8 in Sam’s Teach Yourself C++ in One Hour a Day, 8th Edition.

References are essentially aliases. To use a reference, an ampersand (&) is used on the l-value after the type. When a reference is defined, it takes on the value of the variable assigned to it. As a result, both the reference and the original variable can be used interchangeably. The value can  be update by changing either the original variable or the reference variable.

int x = 42;
int & intRef = x; // create reference to x
x = 30; // value of intRef is also 30
intRef = 19; // value of x is changed to 19, too

References are especially useful when passing parameters to functions. When passing a parameter by value to a function, the variable is copied onto the stack, and the copy is processed in the function. All the while, the original variable remains unchanged.

When passing a variable by reference, the function is able to skip the copying step and deal with the variable directly. This is helpful when you are dealing with large objects. It is recommended to use const qualifier as needed to ensure the function caller has only the minimum permission needed to process data.

double Area(const double & radius, const double & height) {...}

Lastly, you are not allowed to assign a const reference to a non-const reference. The reason being is that, by definition, a const reference’s value is unable to be changed. If it were allowed to be assigned to a non-const reference, then it would be able to be changed. This defeats the whole purpose of declaring it as const in the first place.

int x = 42;
const int & y = x; // const reference cannot be changed
y = 30; // NOT allowed
int & z = y; // const to non-const NOT allowed