How could I send a pointer to a function with reference? I mean, I would like to change where the pointer is poiting in that function.
I have seen for this the double pointer, like for example:
Abc* p;
function(&p);
function(Abc** p){
(*p) = 0;
}
But, I have been told that this is not the best way to approach it. How could be better? Would this work? :
Abc* p;
function(p);
function(Abc* p){
p = 0;
}
Thanks
No, that will not work. That will copy the value of p
into the function and then only modify that copy.
The most appropriate way to pass something by reference in C++ is to use a reference type. They are denoted with an ampersand in the type. You could take a reference to pointer:
Abc* p;
function(p);
void function(Abc*& p){
p = 0;
}
This means that, even though you passed p
directly, it is not copied into the function. The p
argument is a reference to the object passed in.