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?
#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.