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.
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:
Here, x is an integer with value 10. We create a reference ref to x.
Important characteristics of references:
- Initialization:
Referencesmust be initialized when created: - Constant Aliases: Once initialized, a
referencecannot be changed to refer to another variable:
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:
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.
To access the value at the address a pointer holds, we use the * operator, called dereferencing:
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.
