C++ · Beginner level

Beginner level · Module 4: References, Pointers and First Classes · Lesson 1 of 3

References and Pointers

See how variables live at memory addresses, and use references and pointers to refer to them.

In this lesson you will

  • Explain what a pointer stores and how to dereference it
  • Choose references over pointers when no 'no object' value is needed

Key concepts

address-of &dereference *nullptrdangling pointer

The lesson

Every variable occupies memory with an address. &x gives the address of x, and a pointer stores an address: int* p = &x;. *p dereferences the pointer, reading or changing the value it points to.

A pointer can hold nullptr, meaning it points to nothing; dereferencing nullptr is undefined behaviour, so check before using it. A dangling pointer points to memory that no longer exists, such as a local variable from a function that has returned — another source of undefined behaviour.

A reference is another name for an existing object and must be initialised: int& r = x;. It cannot be null or reseated. Prefer references for function parameters, and use pointers when 'no object' is a valid case or the target must change.

Step by step

  1. Print a variable's value and its address.
  2. Create a pointer to it, change the value through the pointer and print again.
  3. Set the pointer to nullptr and add a check before dereferencing.
  4. Rewrite a pointer parameter as a reference.

Practice activity

Write a swap function twice — once with references and once with pointers — and explain which is clearer.

Expected result: Both versions swap two integers correctly, and the learner explains why the reference version is preferred.

Check your understanding

  1. What does *p mean when p is a pointer?

    Show answer

    The object that p points to.

  2. Can a reference be null?

    Show answer

    No; a reference must refer to an existing object.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.