0

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?

user1084113
  • 932
  • 3
  • 15
  • 31
  • For future reference here is the thread for the reasoning behind this question http://stackoverflow.com/questions/1898524/difference-between-pointer-to-a-reference-and-reference-to-a-pointer – user1084113 Jul 11 '12 at 19:01

1 Answers1

3

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;
}
marcinj
  • 48,511
  • 9
  • 79
  • 100