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

C++Server Side ProgrammingProgramming

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
raja
Published on 18-Jun-2019 12:33:19
Advertisements