Pointers and References
Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 13 of 104.
Now that you understand stack and heap memory, let's explore the tools that let you work with memory locations directly: pointers and references.
A pointer stores the memory address of another variable. You declare it with * and get an address using &.
int value = 42;
int* ptr = &value; // ptr holds the address of value
std::cout << ptr; // Prints the memory address
std::cout << *ptr; // Dereference: prints 42A reference is an alias for an existing variable. Once bound, it always refers to that variable. You declare it with &.
int value = 42;
int& ref = value; // ref is an alias for value
ref = 100; // Changes value to 100
std::cout << value; // Prints 100Key differences:
| Pointers | References |
|---|---|
| Can be null | Must be initialized |
| Can be reassigned | Cannot be rebound |
Use * to access value | Access value directly |
| Can point to nothing | Always valid |
Both are essential for passing objects to functions efficiently without copying, and for working with heap-allocated memory. References are safer and simpler, while pointers offer more flexibility when you need to reassign or check for null.
Challenge
EasyLet's build a simple value manipulation system that demonstrates how pointers and references work differently when modifying data.
You'll create two files to organize your code:
ValueOps.h: Define three functions that modify integer values in different ways:doubleByPointer(int* ptr)— takes a pointer and doubles the value it points totripleByReference(int& ref)— takes a reference and triples the valueswapValues(int* a, int* b)— takes two pointers and swaps the values they point to
main.cpp: Read two integers from input, then demonstrate both pointers and references:- Print the original values:
"Original: <first> <second>" - Use
doubleByPointeron the first value, then print:"After double: <first>" - Use
tripleByReferenceon the second value, then print:"After triple: <second>" - Use
swapValuesto swap both values, then print:"After swap: <first> <second>"
- Print the original values:
When calling functions with pointers, remember to use the address-of operator (&) to pass the variable's address. References work more naturally — just pass the variable directly.
Include your header file in main.cpp using #include "ValueOps.h".
Cheat sheet
A pointer stores the memory address of another variable. Declare it with * and get an address using &:
int value = 42;
int* ptr = &value; // ptr holds the address of value
std::cout << ptr; // Prints the memory address
std::cout << *ptr; // Dereference: prints 42A reference is an alias for an existing variable. Declare it with &:
int value = 42;
int& ref = value; // ref is an alias for value
ref = 100; // Changes value to 100
std::cout << value; // Prints 100Key differences:
| Pointers | References |
|---|---|
| Can be null | Must be initialized |
| Can be reassigned | Cannot be rebound |
Use * to access value | Access value directly |
| Can point to nothing | Always valid |
When calling functions with pointers, use the address-of operator (&) to pass the variable's address. References work directly — just pass the variable.
Try it yourself
#include <iostream>
#include "ValueOps.h"
using namespace std;
int main() {
// Read two integers from input
int first, second;
cin >> first;
cin >> second;
// Print original values
cout << "Original: " << first << " " << second << endl;
// TODO: Use doubleByPointer on first value (pass address using &)
// TODO: Print after double
// TODO: Use tripleByReference on second value (pass variable directly)
// TODO: Print after triple
// TODO: Use swapValues to swap both values (pass addresses using &)
// TODO: Print after swap
return 0;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container