Why do we pass a Pointer by Reference in C++?


If we need to modify a pointer rather than the object that the pointer is pointing to, we pass a pointer by reference.

Here is an example of how to pass a pointer by reference −

Example

 Live Demo

#include <iostream>
using namespace std;
void Decrement( int*& d ) {
   --d;
}
int main( void ) {
   int a = 26;
   int* ptr = &a; // pointer to pass
   // print before decrement
   cout<<"Before: "<< ptr << endl;
   Decrement( ptr);
   // print after increment
   cout<<"After: " << ptr;
   return 0;
}

Output

Before: 0x6ffe3c
After: 0x6ffe38

Updated on: 30-Jul-2019

683 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements