C++ References & Pointers

Aliases, addresses and smart pointers.

✍️ 2 exercises in this lesson
  • A reference is another name for an existing variable: int& r = x;. It must be initialised and cannot be re-seated.
  • A pointer stores an address: int* p = &x;, read with *p.
  • nullptr is the null pointer.

Smart pointers

Instead of new/delete, modern C++ uses std::unique_ptr and std::shared_ptr (from <memory>), which free memory automatically.

Key Takeaways: C++ References & Pointers

Mastering C++ References & Pointers helps you write clean and reliable C++ code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

C++ References & Pointers Code Example

C++
#include <iostream>
#include <memory>

int main() {
    int x = 10;
    int& ref = x;
    int* ptr = &x;

    ref += 5;
    *ptr *= 2;
    std::cout << "x = " << x << "\n";

    auto box = std::make_unique<int>(99);
    std::cout << "unique_ptr holds " << *box << "\n";
    return 0;   // box frees its memory automatically
}
Output
x = 30
unique_ptr holds 99
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C++ References & Pointers Practice Exercises

Check what you learned in “C++ References & Pointers”.

/ 2 solved
Fill in the blank

Create a smart pointer that frees memory automatically.

auto box = std::<int>(99);
✓ Correct! Not quite. Try again.
Multiple choice

What is the modern null pointer literal?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services