C++ References Notes
By The Cherno | Full Playlist π
1. What are References?
π Key Idea: References are aliases for existing variables (syntax sugar for pointers).
- Must reference an existing variable (cannot be null).
- No memory allocation: References donβt occupy memory; theyβre just another name for the original variable.
- Syntax: Use
&in the type declaration (not as an operator).
Example:
int a = 5;
int& ref = a; // ref is an alias for a
ref = 2; // Now a = 2
2. References in Functions
Use references to modify variables outside a function without pointers.
Problem with Pass-by-Value:
void increment(int value) { value++; }
int main() {
int a = 5;
increment(a); // a remains 5 (copy passed)
}
Solution with References:
void increment(int& value) { value++; }
int main() {
int a = 5;
increment(a); // a becomes 6
}
3. References vs. Pointers
| References | Pointers |
|βββββββββββ-|βββββββββββββ|
| Must reference an existing variable | Can point to null or uninitialized memory |
| Cannot be reassigned | Can be reassigned to point elsewhere |
| No dereferencing needed (*) | Require dereferencing (* or ->) |
Example:
int a = 5, b = 8;
int* ptr = &a; // Pointer to a
ptr = &b; // Now points to b
int& ref = a; // Reference to a
// ref = b; // Sets a = 8 (does NOT make ref reference b)
4. Key Limitations of References
- Must be initialized:
int& ref; // β Error: references must be initialized - Cannot be reassigned:
int a = 5, b = 8; int& ref = a; ref = b; // Sets a = 8 (does NOT change ref to reference b)
When to Use References?
- Modify function parameters (cleaner than pointers).
- Alias complex variables (e.g.,
std::string&). - Avoid copying large data structures (e.g.,
const vector<int>&).
Cheat Sheet
- Declare Reference:
Type& ref = variable; - Function Parameter:
void func(Type& param) { ... } - Const Reference:
const Type& ref(read-only access).
| Full Video π | Playlist π |
π‘ Pro Tip: Use references for cleaner code when you donβt need pointer flexibility!
