References

Reference variables and their usage

Interview Relevant: Key C++ concept

References in C++

References are aliases for existing variables, providing an alternative name.

Reference Types

  • Lvalue Reference (&): Reference to a named variable
  • Rvalue Reference (&&): Reference to temporary values (C++11)
  • const Reference: Read-only reference

References vs Pointers

  • References cannot be null; pointers can
  • References cannot be reassigned; pointers can
  • References have cleaner syntax; no need for * or &
  • References must be initialized when declared

Code Examples

Lvalue references, const references, and rvalue references.

cpp
1int x = 10;
2int& ref = x;  // ref is an alias for x
3ref = 20;      // x is now 20
4
5// const reference
6const int& cref = x;  // Cannot modify x through cref
7// cref = 30;  // Error!
8
9// Reference as function parameter (pass by reference)
10void swap(int& a, int& b) {
11    int temp = a;
12    a = b;
13    b = temp;
14}
15
16int a = 1, b = 2;
17swap(a, b);  // a=2, b=1
18
19// Const reference for efficiency (no copy)
20void print(const std::string& str) {
21    std::cout << str << std::endl;
22}
23
24// Rvalue reference (C++11)
25int&& rref = 42;  // Reference to temporary
26std::string&& temp = std::string("Hello");

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In