Refefence types - Using of reference
References are commonly used with parameters to functions. The default mechanism used by C++ when calling a function, is to pass arguments into the parameters of that function, by value. This means that only the value is passed. This has one effect in a program as we see:
The pass by value behavior shows that we only passed in a copy of the value that is held in num and not a reference to num itself. Therefore any changes inside the passByValue() function only impact the local variable num1 and not the original variable num.
If we wanted to modify num inside our passByValue function, we would need to pass in a reference, not a value. The following code sample changes the function name, only to make it logical what the function is doing, and the way the parameter is passed in.
Because we passed num as a reference, C++ was able to access the contents of num directly in memory rather than a copy of the value held by num as in the passByValue() example.
Last updated