Pass Pointer by Reference in C+

  1. Use the &var Notation to Pass Object by Reference
  2. Use the *&var Notation to Pass a Pointer to Object by Reference

This article will demonstrate multiple methods about how to pass a pointer by reference in C++.

Use the &var Notation to Pass Object by Reference

Generally, a reference defines an alias for the object in C++, and it must be initialized during the declaration. The initialized reference remains bound to the given object, and it can’t be rebound to another object. Operations on the references modify the bound objects themselves. Thus, they are a common way to pass parameters to functions. References are the preferred method as using them avoids the implicit copying of the objects to the callee function scope. The next example demonstrates the passing of a std::vector object by const reference to the function that searches through the elements for the given value.

#include <iostream>
#include <vector>

using std::cout; using std::vector;
using std::endl; using std::string;

void findInteger(const vector<int> &arr, int k) {
    for (auto &i : arr) {
        if (i == k) {
            cout << "found - " << k << " in the array" << endl;
            return;
        }
    }
    cout << "couldn't find - " << k << " in the array" << endl;
}

int main() {
    vector<int> vec = { 11, 21, 121, 314, 422, 4, 242};

    findInteger(vec, rand() % 100);

    return EXIT_SUCCESS;
}

Output:

couldn t find - 83 in the array

Use the *&var Notation to Pass a Pointer to Object by Reference

On the other hand, we can use the *&var notation to pass a pointer by reference to the function. A pointer is an object itself. It can be assigned or copied to pass a reference to a pointer as a function parameter. In this case, the & symbol is a reference notation and not the address-of operator used to retrieve the pointer to the object’s location in memory. Notice that the passed object’s value should be accessed with the standard pointer dereference operator - *. The below sample code prints the ASCII values of the given string object to cout stream.

#include <iostream>
#include <vector>

using std::cout; using std::vector;
using std::endl; using std::string;

void printASCII(string *&str) {
    for (auto &i : *str) {
        cout << (int)i << ", ";
    }
    cout << endl;
}

int main() {
    auto str = new string("Arbitrary string");

    printASCII(str);

    return EXIT_SUCCESS;
}

Output:

65, 114, 98, 105, 116, 114, 97, 114, 121, 32, 115, 116, 114, 105, 110, 103,
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - C++ Pointer

  • Check if Pointer Is NULL in C++
  • Return a Pointer in C++