Skip to content

Copies and References

The Course
•
35 min study

Suppose you write a helper called add_break that should add a five-minute break to a session. You pass it your session length, it adds 5, and afterward the session in main is exactly as long as before. Nothing is broken: C++ did what you asked. By default a parameter is a copy of the argument, and changing a copy does not change the original. When a function really is meant to update the caller's variable, you must say so with a reference.

A reference parameter, written int&, is not a new integer. It is another name for the caller's integer. Everything you do through that name, including assignment, happens to the original object. This difference between value semantics (work on a copy) and reference semantics (work on the original) runs through all of C++, and choosing between them on purpose is a core skill.

Predict and run

show_copy and add_break have the same body. Only one character differs in their parameters.

Predict before running C++
#include <iostream>

void show_copy(int minutes) {
    minutes += 5;
    std::cout << minutes << "\n";
}

void add_break(int& minutes) {
    minutes += 5;
}

int main() {
    int minutes = 20;
    show_copy(minutes);
    std::cout << minutes << "\n";
    add_break(minutes);
    std::cout << minutes << "\n";
    return 0;
}
Check your prediction
Text
25
20
25

show_copy changed its own local copy to 25 and printed it, then the copy was destroyed when the call ended. main's variable still held 20. add_break received a reference, so minutes += 5 changed main's variable directly. Remove the & from add_break and predict the final line before you run.

A reference must refer to something

A reference is bound to an object when it is created and stays bound to that same object. There is no "empty" reference. That is why you cannot pass a plain number to an int& parameter: a literal like 25 is not a variable that could be changed.

C++
add_break(25);   // error: there is no variable for the reference to name
Shell
main.cpp:13:5: error: no matching function for call to 'add_break'
note: candidate function not viable: expects an lvalue for 1st argument

An "lvalue" is roughly a named object that has a place in memory. The message is the compiler protecting you: a function that promises to change its argument needs an argument that can be changed.

Return a value or update in place

Both styles below add a break. The first returns a new value; the second updates the caller's variable.

Two ways to add a break C++
#include <iostream>

int with_break(int minutes) {
    return minutes + 5;
}

void add_break(int& minutes) {
    minutes += 5;
}

int main() {
    int a = 20;
    int b = 20;
    int longer = with_break(a);
    add_break(b);
    std::cout << a << " " << longer << " " << b << "\n";
    return 0;
}
Text
20 25 25

The returning version leaves a alone and makes the change visible at the call site: longer = with_break(a) clearly produces something new. The reference version is shorter to call, but add_break(b) gives no visual hint that b changes. Prefer returning a value. Use a reference parameter when updating the caller's object is the whole point of the function, or when a function must produce more than one result, as in the practice below.

A reference must not outlive its object

A local variable is destroyed when its function returns. A reference to it would then name an object that no longer exists. That is called a dangling reference, and using one is undefined behavior.

C++
int& broken() {
    int minutes = 25;
    return minutes;   // the reference outlives the variable it names
}

The compiler warns that it is returning a reference to a local variable, and a local build with -Werror turns that warning into an error; the browser editor builds without that flag, so there it may run and print garbage. The fix is to return by value, int broken(), which hands the caller its own copy. Keep the rule simple for now: references are for naming objects that already exist and will keep existing while you use them.

Practice

Exercise

Your turn

Write void add_session(int& total, int& count, int minutes) that adds minutes to total and increases count by one. In main, start both at 0, call it for sessions of 25, 10 and 40, and print 3 sessions, 75 minutes.

Your workspace C++
#include <iostream>

int main() {
    int total = 0;
    int count = 0;
    // Define add_session above main, then call it three times.
    std::cout << count << " sessions, " << total << " minutes\n";
    return 0;
}
Hint 1: the idea

The function produces two results, and both belong to the caller, so both of those parameters must be references. The duration is only read, so a copy is fine.

Hint 2: a first step

Start with an empty body, void add_session(int& total, int& count, int minutes) {}, and make the three calls in main. It compiles and prints 0 sessions, 0 minutes: the calls work, but nothing changes yet. Now make the body update one result at a time, running after each.

Show one solution
Run the solution C++
#include <iostream>

void add_session(int& total, int& count, int minutes) {
    total += minutes;
    ++count;
}

int main() {
    int total = 0;
    int count = 0;
    add_session(total, count, 25);
    add_session(total, count, 10);
    add_session(total, count, 40);
    std::cout << count << " sessions, " << total << " minutes\n";
    return 0;
}
Text
3 sessions, 75 minutes

total and count are references, so every call updates main's two variables; minutes is a value, so the caller can pass a plain number. Remove either & and that result stays at 0, which is a quick way to prove which parameters really are references. Next you will write automatic checks with assert, so a function's promises are tested every time the program runs.

Was this article helpful?

Your response is saved on this device.