CurriculumReferences
References
A reference is an alias for an already existing variable. Once initialized, a reference acts exactly like the original variable. It is a safer, cleaner alternative to pointers for many common tasks in C++.
01Creating a Reference
To create a reference, use the
Once created, whatever you do to the reference happens to the original variable. They share the same memory location.
& symbol in the type declaration. Once created, whatever you do to the reference happens to the original variable. They share the same memory location.
main.cpp
Terminal
Waiting for execution...
Visualizer
Run code to see reference.
02Pass by Value vs Reference
Let's compare them side-by-side.
Pass by Value (
Pass by Reference (
Pass by Value (
int hp) gives the function a copy. Modifying it doesn't affect the original.Pass by Reference (
int& hp) gives the function the original variable. Modifying it changes the original immediately!main.cpp
Terminal
Waiting for execution...
Visualizer
Run code to see reference.
03Const References
What if you have a massive object (like a 100MB 3D Model) and want to pass it to a function without copying it, but you also want to prevent the function from modifying it?
Enter the
Enter the
const reference. It gives read-only access to the original object.main.cpp
Terminal
Waiting for execution...
04References vs Pointers
References and Pointers do similar things (access memory indirectly), but they have strict differences:
1. References must be initialized immediately.
2. References cannot be null.
3. References cannot be reassigned to point to another variable later.
Pointers can do all three. Use references when you can, and pointers when you have to.
1. References must be initialized immediately.
2. References cannot be null.
3. References cannot be reassigned to point to another variable later.
Pointers can do all three. Use references when you can, and pointers when you have to.
main.cpp
Terminal
Waiting for execution...
AI Tutor
References allow you to pass large objects to functions without the performance penalty of copying them, and without the messy syntax of pointers.