Lesson 13 — Memory Management

References

A reference is an alias for an existing variable. Unlike a pointer, it cannot be null, cannot be reassigned to refer to something else, and requires no dereferencing syntax.

Creating a Reference

A reference is declared with & at the point of declaration, and must be initialised immediately — it always refers to the same variable for its entire lifetime.

C++ — Reference basics
int score = 90;
int &scoreRef = score; // scoreRef is now another name for score

scoreRef = 95;
std::cout << score << std::endl; // 95 — same variable, two names

References vs Pointers

References and pointers solve similar problems but have different rules. Understanding when to reach for each will make your function signatures clearer.

  • A reference must be initialised when declared; a pointer can be declared and assigned later.
  • A reference cannot be null; a pointer can be nullptr.
  • A reference cannot be reseated to refer to a different variable; a pointer can be reassigned.
  • References use plain variable syntax; pointers require * to dereference.

Common Mistakes

  • Trying to declare a reference without initialising it immediately — this will not compile.
  • Assuming a reference can be "reseated" to point elsewhere like a pointer — reassigning it changes the value, not what it refers to.
  • Returning a reference to a local variable from a function, which becomes invalid once the function ends.
  • Overusing references for simple built-in types like int where pass-by-value is simpler and just as fast.

Professional Tip

Use references for function parameters when you want the clarity of normal variable syntax with the efficiency of avoiding a copy — especially for objects like std::string or std::vector. Reserve raw pointers for cases where "no value" (nullptr) is a meaningful state.

Your Turn

Write a function void swapValues(int &a, int &b) that swaps the values of two integers using references, then call it in main() and print the results before and after.

Mini Quiz

Which of these is true about references but NOT true about pointers?