Sub topic 1
References as aliases
References as aliases
A reference is another name for an existing object. An object is a place in memory that holds a value, such as an int variable.
Write int& to declare a reference to an int. You must give the reference an object when you create it. This connection is called binding.
Once bound, a reference cannot be changed to refer to another object. Assigning a value through it changes the original object instead.
Binding and const references
A const reference gives read-only access through that name. For example, const int& can refer to an int, but you cannot use the reference to change its value.
The object may still change through another name. A const reference to that object will then read the new value.
Passing arguments by reference
A function is a named set of instructions. A parameter is a name a function uses for a value passed to it.
A reference parameter lets the function access the caller’s object without making a separate copy. Use int& when the function needs to change the object. Use const int& when it only needs to read the object.
Returning references
A function can return a reference to an object. The caller can then use the result to access that same object.
Do not return a reference to a local variable, which is a variable created inside the function. The variable stops existing when the function ends.
Worked example
This program uses a reference to change value. It then changes value through a function parameter and through a returned reference.
#include <iostream>
void add_one(int& number) {
number += 1;
}
int read(const int& number) {
return number;
}
int& access(int& number) {
return number;
}
int main() {
int value = 3;
int& alias = value;
alias = 7;
const int& view = value;
add_one(value);
access(value) = 9;
std::cout << "value: " << value << '\n';
std::cout << "view: " << read(view) << '\n';
}The program prints value: 9 and view: 9. The read-only view sees the change because it refers to the same object.
Exercise
If you replace alias = 7; with alias = 5;, which object changes?
Show answer
value changes to 5 because alias refers to it.