OneCompiler

"Pass by Reference" Made Easy

Pass by Reference in C++

"Pass by reference" in C++ is a way of passing arguments to functions in which a reference (or an alias) to the actual variable is passed instead of a copy. This means that any changes made to the parameter inside the function directly affect the original variable outside the function.

Concrete Intuition:

Think of "pass by reference" like giving someone the keys to your house instead of a picture of your house. When you give them your keys, they can enter your house, rearrange furniture, change the lock, or even paint the walls. Any changes they make happen directly to your house, and when you get your keys back, your house looks different because they had direct access to it.

  • Your House (Variable): This represents your actual data in memory.
  • Keys (Reference): These are given to someone (the function) to access and modify your house (variable).
  • Changes: Any modifications made inside your house will be evident when you return, just like how changes within the function reflect on the original variable.

Example in C++:

#include <iostream>

void modifyValue(int &num) { // Notice the '&' indicating pass by reference
    num = num + 10; // Modify the number
   cout << "Inside modifyValue: " << num << endl; // Prints modified value
}

int main() {
    int originalValue = 5;
    cout << "Before modifyValue: " << originalValue << endl; // Prints original value
    modifyValue(originalValue); // Passing the reference to the function
    cout << "After modifyValue: " << originalValue << endl; // Prints modified value
    return 0;
}

What Happens Here:

  1. Before Calling the Function:

    • originalValue is set to 5.
  2. Function Call:

    • When modifyValue(originalValue); is called, a reference to originalValue is passed to the function modifyValue.
  3. Inside the Function:

    • The num inside modifyValue acts as an alias for originalValue; they refer to the same memory location.
    • When we change num to num + 10, it actually changes originalValue to 15.
  4. After the Function Call:

    • After the function finishes executing, originalValue is now 15, because the function modified the original variable directly.

Key Points:

  • Changes made to num within modifyValue affect originalValue because they point to the same data.
  • You declare a reference parameter by using an ampersand (&) in the function’s parameter list.

Summary:

When you use pass by reference, you are allowing the function to work directly with the original variable. Just like the person with the keys can affect your home directly, a function that receives a reference can change the original variable directly. This method is useful when you want to directly modify the value or when passing large objects to avoid the overhead of copying data. Understanding pass by reference ensures clarity in how data can be manipulated within functions in C++.