Understanding References and Pointers

Welcome! Today, we are going to learn about something very important in C++: references and pointers. This might sound a bit challenging, but I'll break it down for you with simple explanations and examples. By the end of this lesson, you'll understand what references and pointers are, when to use them, and how they can make your code more powerful.

Our goal is to get comfortable with these concepts so you can manage memory more efficiently and write clearer and more efficient code.

Understanding what References are

A reference in C++ is like a nickname for a variable. Imagine a friend named Alex, who you call "Al." "Al" is just another name for Alex. Similarly, a reference is another name for a variable.

In C++, we use the & symbol to create a reference. Here’s the basic syntax:

int x = 10;
int &ref = x; // ref is now a reference to x

Here, x is an integer with value 10. We create a reference ref to x.

Important characteristics of references:

  1. Initialization: References must be initialized when created:
    int y = 5;
    int &ref = y; // Correct: ref is initialized with y
    // int &r; // Error: reference must be initialized
  2. Constant Aliases: Once initialized, a reference cannot be changed to refer to another variable:
    ref = 20; // This sets y (and hence ref) to 20, doesn't reassign ref
Understanding what Pointers are

A pointer stores the address of another variable, like a treasure map showing where the treasure is buried. Think of the pointer as the map and the variable as the treasure.

In C++, we use the * symbol to define a pointer. Here’s the basic syntax:

int x = 10;
int *ptr = &x; // ptr now holds the address of x

Here, x is an integer value, and ptr is a pointer, showing where to find x. Note that the pointer can be assigned only to a reference of the target variable.

Dereferencing a Pointer

To access the value at the address a pointer holds, we use the * operator, called dereferencing:

int z = 30;
int *ptr = &z; // ptr points to z
*ptr = 40; // changes the value of z to 40
std::cout << z; // 40

In this code, we change the value through the pointer instead of using its name directly. To do it, we firstly dereference the pointer with the * operator.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal