Lets say I have a class “A” and this function:
void initializationFunction(A* classPointer)
{
...
...
classPointer = new A(.....);
}
I write:
A* classPointer;
Then I pass this pointer to this function:
initializationFunction(classPointer);
This will not work unless I pass it by reference in the function declaration:
void initializationFunction(A*& classPointer);
I thought reference passing was for non-pointer type variables. I mean you don’t need to pass an array by reference…
Thanks for the explanations 🙂
Yeah, that is true. You’ve to pass the argument by reference (or you can pass
A**instead).But the best solution is to write the constructor of
Ain such way that you wouldn’t need this function in the first place. That is, whatever you’re doing in this function, you should be doing that in the constructor itself.If, however, you cannot edit the class, then you can do this instead:
In my opinion, this approach is better than yours.
Note I didn’t change the name of the function and other variables. I guess that isn’t the point of the post. But I believe you would want better names for real code.