Reputation: 962
So I have a class that has a protected pointer member of the following type
int *assigntoThis; // In the constructor I have initialized this to NULL.
I also have a public recursive member function of the same class with the following declaration
bool find(int* parent, std::string nameofnode, int* storeParentinThis);
The recursive function checks through child nodes and if the name of the child Node matches the string passed in as a parameter it will assign the address of parent to storeParentinThis.
This is how I call the function from another function of the same class.
bool find(root, "Thread", assigntoThis);
However, during runtime when I output the value stored in assigntoThis I get 00000000 = NULL. How do I change the value of assigntoThis inside my recursive function?
Upvotes: 0
Views: 2190
Reputation: 49986
change to :
bool find(int* parent, std::string nameofnode, int*& storeParentinThis);
explanation:
here is a simplified version of your original code:
foo (int* p) { /// p bahaves as a local variable inside foo
p = 1;
}
int* p = 0;
foo(p);
// here p is still equal 0
this is actually similar to following code:
foo (int i) {
i = 1;
}
int i = 0;
foo(i);
// here i is still equal 0
which I think is easier to understand.
So if we want to return something from a function we must make a pointer to it or a reference to it, going backwards with examples:
foo (int* i) { // pointer example
*i = 1;
}
int i = 0;
foo(&i);
// here i is equal to 1
foo (int& i) { // using reference example
i = 1;
}
int i = 0;
foo(i);
// here i is equal to 1
Now it is easy to apply it to your case:
// pointer example
bool find(int* parent, std::string nameofnode, int** storeParentinThis) {
*storeParentinThis = parent;
}
// reference example
bool find(int* parent, std::string nameofnode, int*& storeParentinThis) {
storeParentinThis = parent;
}
Upvotes: 3