Skip to content

C++ References

Overview

References are aliases for existing variables. They provide an alternative name to access the same memory location.

Basic References

cpp
#include <iostream>

int main() {
    int value = 42;
    int& ref = value;  // reference to value
    
    std::cout << "Value: " << value << std::endl;
    std::cout << "Reference: " << ref << std::endl;
    
    ref = 100;  // modifies the original value
    std::cout << "New value: " << value << std::endl;
    
    return 0;
}

References as Function Parameters

cpp
#include <iostream>

// Pass by reference - modifies original
void increment(int& num) {
    num++;
}

// Pass by const reference - read-only access
void printValue(const int& num) {
    std::cout << "Value: " << num << std::endl;
}

int main() {
    int number = 10;
    
    std::cout << "Before increment: " << number << std::endl;
    increment(number);
    std::cout << "After increment: " << number << std::endl;
    
    printValue(number);
    
    return 0;
}

Reference Return Values

cpp
#include <iostream>

class Array {
private:
    int data[5];
    
public:
    Array() {
        for (int i = 0; i < 5; i++) {
            data[i] = i * 10;
        }
    }
    
    // Return reference to allow modification
    int& operator[](int index) {
        return data[index];
    }
    
    // Return const reference for read-only access
    const int& operator[](int index) const {
        return data[index];
    }
};

int main() {
    Array arr;
    
    std::cout << "arr[2] = " << arr[2] << std::endl;
    
    arr[2] = 999;  // modifies through reference
    std::cout << "arr[2] = " << arr[2] << std::endl;
    
    return 0;
}

References vs Pointers

cpp
#include <iostream>

void demonstratePointers() {
    int value = 42;
    int* ptr = &value;
    
    std::cout << "Pointer value: " << *ptr << std::endl;
    ptr = nullptr;  // can be reassigned
}

void demonstrateReferences() {
    int value = 42;
    int& ref = value;
    
    std::cout << "Reference value: " << ref << std::endl;
    // ref = another_value;  // can't reassign reference
}

Content is for learning and research only.