Skip to content

References and const-correctness

Beginning of the lesson

References and const-correctness

Give a variable a second name, and let const guard your intentions

Big Idea: A reference is an alias — a second name that binds to an existing object and shares its identity. Add const and you gain a compiler-enforced promise: "I will read this, but I will not modify it." Together, references and const let you pass large objects cheaply, write self-documenting interfaces, and catch a whole class of bugs at compile time instead of at 3 a.m. in production.
By the end of this lesson you will be able to:
  • explain what an lvalue reference is and how it differs from a pointer,
  • pass parameters by const reference to avoid copies without risking mutation,
  • write const member functions and understand what they guarantee,
  • reason about why const-correctness makes larger programs safer and clearer.

1. What exactly is a reference?

An lvalue reference is a name that refers to an object that already exists. When you write int& r = x;, you are not making a copy of x and you are not creating a new object — you are giving the same object a second name. From that point on, r and x are two labels on one box in memory.

Two rules define a reference and separate it from every other C++ tool:

  • It must be initialized. There is no such thing as an uninitialized reference. int& r; does not compile — a reference must bind to something the moment it is born.
  • It can never be re-seated. Once r refers to x, it refers to x for its entire life. Writing r = y; does not make r point at y; it copies the value of y into x.
#include <iostream>

int main() {
    int x = 10;
    int& r = x;      // r is another name for x
    r = 20;          // writes through r -> changes x
    std::cout << x << '\n';   // prints 20

    int y = 99;
    r = y;           // NOT re-seating: copies y's value into x
    std::cout << x << '\n';   // prints 99
    std::cout << &r << " == " << &x << '\n'; // same address
}

Because r and x share one address, taking &r and &x yields the identical pointer. A reference has no separate storage of its own that you can observe — it truly is the object under another name.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers