recursion & object life

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi!

Please read the code snippet below. What it is supposed to produce a chain:
first_node(value = 0) --> next_node(value =5) --> next_node(value =10) -->
next_node(value = 15)

However, I fear that objects created in deep levels of recursions are
ultimately detroyed, although they are returned one level up. So, please help
me if you know how to rectify this code and achieve the desired result. I
need all the objects created during the recursions to be alive when I get
back to the top level.

Thanks in advance,
Ido




===========================================

class node
{
public:
node * next_node;
int value;

node() {
next_node = NULL;
value = 0;
};
};

node MyRecursive(node previous_node)
{
node current_node;
current_node.value = (previous_node.value + 5);
previous_node.next_node = &(current_node);
if (current_node.value < 20) MyRecursive(current_node);
else return previous_node;
}


int _tmain(int argc, _TCHAR* argv[])
{
node first_node;
first_node = MyRecursive(first_node);
return first_node.value;
}
 
Your code is incorrect (and dangerous). When you leave a method, any local
objects created (normally on the stack) are destructed. You need to have your
routines use POINTERS to classes and create via a new operator. That way, there
will not be any destruction until you specifically delete the object.

/steveA
Hi!

Please read the code snippet below. What it is supposed to produce a chain:
first_node(value = 0) --> next_node(value =5) --> next_node(value =10) -->
next_node(value = 15)

However, I fear that objects created in deep levels of recursions are
ultimately detroyed, although they are returned one level up. So, please help
me if you know how to rectify this code and achieve the desired result. I
need all the objects created during the recursions to be alive when I get
back to the top level.

Thanks in advance,
Ido




===========================================

class node
{
public:
node * next_node;
int value;

node() {
next_node = NULL;
value = 0;
};
};

node MyRecursive(node previous_node)
{
node current_node;
current_node.value = (previous_node.value + 5);
previous_node.next_node = &(current_node);
if (current_node.value < 20) MyRecursive(current_node);
else return previous_node;
}


int _tmain(int argc, _TCHAR* argv[])
{
node first_node;
first_node = MyRecursive(first_node);
return first_node.value;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top