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:

#include <iostream>
using namespace std;

void passByValue(int); //declare our function prototype before main()

int main()
{
//declare and assign the variable num
int num = 3;
std::cout << "In main()" << std::endl;
std::cout << "Value of num is " << num << std::endl;
//call the passByValue
passByValue(num);

std::cout << "Back in main and the value of num is " << num << std::endl;


return 0;
}

void passByValue(int num1)
{
std::cout << "In passByValue()" << std::endl;
std::cout << "Value of num1 is " << num1 << std::endl;

// modify num1, won't impact num
//Inside passByValue, we increment num1 and output its new value, which in this case is 4.
num1++;

std::cout << "num1 is now " << num1 << std::endl;
}

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.

    #include <iostream>
    using namespace std;

    void passByRef(int &num1);

    int main()
    {

        int num = 3;
        cout << "In main()" << endl;
        cout << "Value of num is " << num << endl;

        passByRef(num);

        cout << "Back in main and the value of num is  " << num << endl;


        return 0;
    }

    void passByRef(int &num1) 
    {
        cout << "In passByRef()" << endl;
        cout << "Value of num1 is " << num1 << endl;

        // modify num1 which will now change num
        num1++;

        cout << "num1 is now " << num1 << endl;
    }

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