Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it OK to pass reference to a pointer as a function argument?

I had the understanding that in c++ & and * cancel each other i.e int *&p is essentially equal to p as its value at address of integer p.

Now is it valid to pass reference to a pointer in view of above i.e say i am trying to pass reference to a pointer as an argument in a function as below?

void func(int* &p)

Won’t the above result in cancellation of * with & and will just be int p?
How correct is it if i try to pass reference to pointer of a class object on similar terms?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <iostream>

using namespace std;

int gobal_var = 42;

// function to change Reference to pointer value
void changeReferenceValue(int*& pp)
{
    pp = &gobal_var;
}

int main()
{
    int var = 23;
    int* ptr_to_var = &var;

    cout << "Passing a Reference to a pointer to function" << endl;

    cout << "Before :" << *ptr_to_var << endl; // display 23

    changeReferenceValue(ptr_to_var);

    cout << "After :" << *ptr_to_var << endl; // display 42

    return 0;
}

>Solution :

You are correct that the & address-of operator and the * indirection operator cancel each other out when used inside an expression.

However, when used inside a declaration, these operators have a very different meaning. Inside a declaration, * means "pointer" and & means "reference". Therefore, when used inside a declaration, they do not cancel each other out.

An object of type int*& is simply a reference to a pointer to an int.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading