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?

1

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.