Menu
References in C++

References in C++

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

Video Reference πŸŽ₯


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
}

Video Reference πŸŽ₯


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)

Video Reference πŸŽ₯


4. Key Limitations of References

  1. Must be initialized:
    int& ref;  // ❌ Error: references must be initialized
    
  2. Cannot be reassigned:
    int a = 5, b = 8;
    int& ref = a;
    ref = b;   // Sets a = 8 (does NOT change ref to reference b)
    

    Video Reference πŸŽ₯


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!