1.5.3 Passing by Reference vs Value

By default, parameters are passed by value in C++. This means the value of a parameter is copied into the function. Changes to the parameter do not change the variable that was originally used in the calling function. This is the same as how arguments are passed in Java.

C++ does offer another option called pass by reference where a value in the function points back to the original value. Let’s explore these two options for C++.

Pass By Value

Take a look at the code below as it runs.

Notice in this example how the value of variable a in the main function does not change when the addFive function adds 5 to the parameter n. That value gets returned and you can see how the original value of a is still 8 and the added value (stored in b) is now 13.

This is the default for a function.

Pass By Reference

In contrast, C++ offers the option to pass by reference. Instead of creating a copy of a variable for the function, C++ uses a pointer back to the variable in the calling function. Any updates to the parameter in the function also updates the variable in the calling function. This is an often used feature.

To pass by reference, add an & before the variable name in the parameter list for the method.

Take a look below at the example as it executes.

If you look at the right hand side, you notice that the parameter n actually points back to the same memory location of a. Instead of making a copy of the variable, it uses the value stored in memory for a. As a result, when the function adds 5 to the parameter n, it is actually adding 5 to the value of a.

When this value is returned to b, you can see that both a and b in the main function are now 13.

Why Use Pass by Reference?

As mentioned above, you will use pass by reference often as you learn to code in C++. There are 2 main use cases for using pass by reference. First, it is very helpful when you want to make changes to several variables in a function. While you can only return one value, if you pass by reference, you can update any number of values in a function and have these updates reflected in the calling function.

The second option is for times when you use large amounts of data, for example when you have a large data structure such as a list. By passing by reference, you can avoid using additional memory to create the copy of the large database.

Last updated