Thuta Learning
C++
IntermediateProgrammingBeginner

References

C++Lesson 1525 min

What you'll walk away with

  • Declare a reference with T& and explain why it must be initialised and can never be re-bound
  • Choose between pass by value, by T& and by const T& for a function parameter
  • Modify container elements in a range-based for with auto& instead of changing copies
  • Spot a dangling reference, such as one returned to a local variable

Explain it simply

Explain it simply

A reference is a second name for a variable that already exists. If your friend Aung is also called "Ko Ko" at home, those are two names for one person: whatever happens to Ko Ko happens to Aung. In C++, std::string& alias = course; makes alias another name for course, and nothing is copied.

References matter most in function parameters. Passing a big string or vector by value copies it; passing it by reference hands the function the caller's own object. Add const, as in const std::string&, and the function can read the original without copying it and without being allowed to change it.

Problem → Why → Solution

The problem: changes that land on a copy

You want to double every price in a list. The loop below compiles, runs, and changes nothing: each iteration copies one element into price, doubles the copy, and throws it away. The same trap appears with functions: a parameter declared as std::vector<int> receives its own copy, so edits inside the function vanish when it returns, and for a big container that copy also costs time and memory on every call.

prices.cpp
#include <iostream>
#include <vector>

void addDiscount(std::vector<int> prices) {     // receives a copy
    for (int& price : prices) price -= 10;
}

int main() {
    std::vector<int> prices{100, 250, 40};
    for (int price : prices) price *= 2;        // doubles a copy
    addDiscount(prices);                        // edits another copy
    std::cout << prices[0] << '\n';             // still 100
}

Why does C++ copy by default?

In C++, a variable of type int or std::vector<int> is a value: initialising one from another makes an independent copy. That is safe and predictable, but it means edits never reach the original unless you ask for a reference. GCC even hints at the loop bug with variable 'price' set but not used. Writing int& price and std::vector<int>& prices makes both names refer to the caller's objects.

Core concept: one object, two names

A reference is declared with & after the type: int& r = x; makes r another name for x. It is not a separate object holding an address the way a pointer is; it is an alias, and every use of r is a use of x. Because of that, a reference must be initialised when it is declared (int& r; fails with 'r' declared as reference but not initialized), and it can never be re-bound to a different variable later.

text
std::string& alias = course;
----------------------------
   course ---+
             +---> [ "Basic C++" ]     one object, two names
   alias  ---+

 alias = other;   copies the text of other INTO course;
                  alias still names course

That last rule surprises people. After int& r = x;, writing r = y; does not make r refer to y. It copies y's value into x, because r is x. A reference also cannot be null in a correct program, which is exactly why it is the natural choice when a value must always be present, while a pointer is the right tool when "nothing" is a legal answer.

Parameters are where references earn their keep, and there are three common shapes. Pass by value, f(std::string s), gives the function its own copy, which is right for small types like int and double or when the function needs a copy anyway. Pass by reference, f(std::string& s), lets the function change the caller's object. Pass by const reference, f(const std::string& s), lets it read a large object without copying, and the compiler rejects any attempt to modify it. A non-const reference also refuses temporaries: shout(std::string("hi")) does not compile when shout takes std::string&, because changing a temporary would be pointless.

ParameterCopies?Can change the caller's object?
T valueyesno
T& valuenoyes
const T& valuenono

A reference never extends the life of the object it names, apart from one special rule for temporaries bound to a const reference. If the object dies first, the reference dangles, just like a pointer.

Mental model: a second name tag on one object
  1. T& r = x; puts a second name on x
  2. Every use of r is a use of x
  3. r = y copies y into x; no rebinding
  4. When x dies, r dangles

Use const T& to read big objects, T& to change them, and plain T for small values.

General pattern

cpp
Type& alias = existing;         // must be initialised, cannot be re-bound

void read(const Type& value);   // no copy, read-only
void change(Type& value);       // no copy, may modify the caller's object
void own(Type value);           // gets its own copy

for (Type& item : container) { /* modify each element */ }
for (const Type& item : container) { /* read without copying */ }

The & goes after the type. In a parameter list it decides whether the function sees the caller's object or a copy, and const decides whether it may change it. The same choice applies to the loop variable of a range-based for.

Example: renaming a course through references

The program gives course a second name, prints it through a const reference, renames it through a non-const reference parameter, and finally shows that assigning to a reference copies a value instead of re-binding the reference.

references.cpp
#include <iostream>
#include <string>

void renameCourse(std::string& courseName) {
    courseName = "Advanced C++";
}

void printCourse(const std::string& courseName) {
    std::cout << "Course: " << courseName << '\n';
}

int main() {
    std::string course = "Basic C++";
    std::string& alias = course;

    printCourse(alias);
    renameCourse(course);
    printCourse(course);

    std::string other = "Rust";
    alias = other;
    other = "Go";
    std::cout << "course: " << course << ", other: " << other << '\n';
}

Code breakdown

  1. Lines 4-6void renameCourse(std::string& courseName) {

    courseName is a reference parameter, so assigning to it inside the function changes the caller's string. No copy of the string is made on the way in.

  2. Lines 8-10void printCourse(const std::string& courseName) {

    const std::string& is the usual way to accept a string you only read: no copy, and the compiler rejects any attempt to modify it.

  3. Line 14std::string& alias = course;

    alias is initialised to name course. There is still only one string in memory.

  4. Line 17renameCourse(course);

    The function receives course itself, so the following printCourse() shows Advanced C++.

  5. Lines 20-23alias = other;

    This does not re-bind alias to other. It copies "Rust" into course, because alias is course. When other later becomes "Go", course keeps "Rust", which proves the two are still separate objects.

You should see
Course: Basic C++
Course: Advanced C++
course: Rust, other: Go

References in range-based for loops

The loop variable of a range-based for is a fresh variable for each element, so its type decides whether you touch the element or a copy. int price copies; int& price refers to the element and can change it; const auto& item refers without copying and without changing, which is the best default for reading strings and other large elements.

tags.cpp
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> tags{"sale", "new", "eco"};

    for (std::string& tag : tags) tag = "#" + tag;   // changes each element

    for (const std::string& tag : tags) {            // reads without copying
        std::cout << tag << ' ';
    }
    std::cout << '\n';                                // #sale #new #eco
}

Dangling references

A reference is only safe while its object lives. The classic mistake is returning a reference to a local variable: const std::string& greeting() { std::string text = "hello"; return text; } returns a name for a string that is destroyed as the function ends, and GCC warns reference to local variable 'text' returned. Returning a reference is fine when the object belongs to the caller, as with lastName() below, which returns a reference into the caller's vector. Even then, the reference becomes invalid if the vector later grows and moves its elements.

last_name.cpp
#include <iostream>
#include <string>
#include <vector>

std::string& lastName(std::vector<std::string>& names) {
    return names.back();   // refers into the caller's vector
}

int main() {
    std::vector<std::string> names{"Aye", "Bo"};
    lastName(names) += " (captain)";
    std::cout << names[1] << '\n';   // Bo (captain)
}

When in doubt, return by value

Returning a std::string or std::vector by value is cheap in modern C++, because the compiler either elides the copy or moves the result. Return a reference only when the object clearly outlives the call.

In real projects

Where this shows up in real projects

const T& parameters are the most common function signature in real C++ code: void log(const std::string& message), double total(const std::vector<Order>& orders). They give value-like safety, since the function cannot change your object, without the cost of a copy, which matters when the argument is a vector of thousands of records. Code reviews routinely flag a std::string or std::vector parameter taken by value when the function only reads it.

Non-const references appear where a function's job is to update something: a sort routine, a function that fills an output vector, or operator overloads such as operator+= that return *this by reference so calls can be chained. Range-based for loops with auto& are the everyday way to update every element of a container. Many style guides, including the C++ Core Guidelines, recommend T& for "must exist" and T* for "may be absent".

Common mistakes

Common mistakes

1. Expecting a reference to re-bind

After int& r = a;, the line r = b; copies b's value into a. If you need something that can switch to a different object later, you need a pointer (or std::reference_wrapper), not a reference.

2. Forgetting the & in a loop or parameter

for (auto item : items) and void update(std::vector<int> v) both work on copies, so updates silently disappear. When a function or loop is meant to modify, check that the & is really there; when it only reads a large object, add const & to avoid the copy.

3. Holding an element reference across push_back()

std::string& first = names[0]; names.push_back("Zaw"); may move every element to new storage, and first then refers to freed memory. Re-read names[0] after changing the vector's size, or reserve() enough space up front.

4. Passing a temporary to T&

shout(std::string("hi")) is rejected with cannot bind non-const lvalue reference of type 'std::string&' ... to an rvalue. If the function does not need to modify its argument, make the parameter const std::string&, which accepts temporaries too.

Best practices

Best practices

  • Take large read-only arguments as const T&; take small types such as int and double by value.
  • Use T& parameters only when the function's purpose is to modify the argument, and make that clear from its name.
  • Use const auto& in range-based for loops that only read, and auto& in loops that modify.
  • Return by value unless the returned object clearly outlives the call.

Mini challenge

Mini challenge: payroll update

Write three small functions for a payroll list, each with the right kind of parameter for its job, then use a returned reference to update an element in place.

  • void applyRaise(std::vector<double>& salaries, double percent) changes every salary in place
  • double total(const std::vector<double>& salaries) reads without copying
  • std::string& longestName(std::vector<std::string>& names) returns a reference to the longest name
  • Append " (team lead)" through the returned reference and print the element from the vector
payroll.cpp
#include <format>
#include <iostream>
#include <string>
#include <vector>

void applyRaise(std::vector<double>& salaries, double percent) {
    // TODO: use a reference loop variable so each salary really changes
}

double total(const std::vector<double>& salaries) {
    // TODO: add up the salaries
}

std::string& longestName(std::vector<std::string>& names) {
    // TODO: find the index of the longest name and return names[index]
}

int main() {
    std::vector<double> salaries{1200.0, 950.0, 1500.0};
    std::vector<std::string> names{"Aye", "Thandar", "Bo"};
    // TODO: print the total, apply a 10% raise, print the new total
    // TODO: append " (team lead)" through longestName() and print names[1]
}

Expected: Before: 3650.00 After 10% raise: 4015.00 Thandar (team lead)

Show hint

Inside applyRaise, for (double& salary : salaries) is what makes the change stick. longestName() must return names[best], an element of the caller's vector, never a local copy.

Show solution
payroll.cpp
#include <format>
#include <iostream>
#include <string>
#include <vector>

void applyRaise(std::vector<double>& salaries, double percent) {
    for (double& salary : salaries) {
        salary *= 1.0 + percent / 100.0;
    }
}

double total(const std::vector<double>& salaries) {
    double sum = 0.0;
    for (double salary : salaries) sum += salary;
    return sum;
}

std::string& longestName(std::vector<std::string>& names) {
    std::size_t best = 0;
    for (std::size_t i = 1; i < names.size(); ++i) {
        if (names[i].size() > names[best].size()) best = i;
    }
    return names[best];
}

int main() {
    std::vector<double> salaries{1200.0, 950.0, 1500.0};
    std::vector<std::string> names{"Aye", "Thandar", "Bo"};

    std::cout << std::format("Before: {:.2f}\n", total(salaries));
    applyRaise(salaries, 10.0);
    std::cout << std::format("After 10% raise: {:.2f}\n", total(salaries));

    std::string& star = longestName(names);
    star += " (team lead)";
    std::cout << names[1] << '\n';
}

Quick quiz 1 / 3

What does this print? int a = 5; int& r = a; int b = 8; r = b; b = 1; std::cout << a;

Quick quiz 2 / 3

A function only reads a std::vector<std::string> holding 10,000 names. Which parameter fits best?

Quick quiz 3 / 3

Which line fails to compile?

What to remember

  • A reference is another name for an existing object: it must be initialised and can never be re-bound.
  • Assigning to a reference assigns to the object it names.
  • Pass large read-only arguments as const T&, use T& only to modify, and pass small types by value.
  • A reference dangles if its object dies first, so never return a reference to a local variable.

C++ Core Guidelines — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

References | Thuta Learning