Pass by reference revolves around the concept of passing a variable address/pointer as an argument to a function.
Instead of making a copy of the variable in the memory, variable references are passed onto the function and manipulated as required.
It will not save old values. Instead, it will fill new values in those memory spaces.
Let’s take a look at an example.
#include <iostream>using namespace std;void passByRef(int &a){a = 8;}int main() {int a = 5;cout << "Old Value:" <<a << endl;passByRef(a);cout << "New Value:" <<a << endl;return 0;}
Below is an illustration explaining the above code.
In C++, primitive data types (such as int
, char
, etc.) are pass by value by default. However, they can be passed by reference using the &
operator.
The non-primitive data types are pass by reference by default, as the reference to the object is passed to the function.
In Java, all data types are passed by values.
To further enhance your understanding, you can compare this concept with pass by value. For a clear picture, check out this answer: Pass by value vs. pass by reference.
Free Resources