0

Thanks for everybody! Now I changed my logic. Since if I contain the same pointer point to itself it will create infinite loop. So for this revised one do I need to write the destructor?

#include <stdio.h>
#include <stdlib.h>
#include <tr1/array>

using namespace std;
class Graphnode {

public:
    std::tr1::array<int, 16> state;
    int x;
    int depth;
    Graphnode(std::tr1::array<int, 16>,int,int);
    Graphnode();
    //~Graphnode();

};
Graphnode::Graphnode()
{
    int i=0;
    for(i=0;i<16;i++)
    {
       state[i] = 0;
    }
    x = 0;
    depth = 0;
}
Graphnode::Graphnode(std::tr1::array<int, 16> _state,int _x,int _d)
{   
    int i=0;
    for(i=0;i<16;i++)
    {
       state[i] = _state[i];
    }
    x = _x;
    depth = _d;
}
/*Graphnode::~Graphnode()
{
}*/
weeo
  • 2,619
  • 5
  • 20
  • 29
  • You are getting infinite recursion in your constructor, since `up`, `down`, `left`, and `right` are all recursively calling the same constructor. Rethink the logic in the way you create new `Graphnode`s. – jli Nov 26 '11 at 21:38
  • 1
    maybe I'm just slow, but what do you mean by "self contained"? – jalf Nov 26 '11 at 21:43
  • so we should never contain a pointer inside itself? – weeo Nov 26 '11 at 21:44
  • I have revised my code. so this will not create recursive calling. I wonder what should I wrote in the destructor? since there is no pointer now do I still need the destructor? – weeo Nov 26 '11 at 21:50
  • @weeo Foo can contain a Foo*, but at least one constructor must initialize that pointer to NULL. If a constructor initializes the pointer by creating a new Foo, it should ensure that the constructor used eventually leads to a "terminal" constructor which does not allocate a new Foo. It is very likely a mistake to try to have a constructor which creates a new Foo. – 01d55 Nov 26 '11 at 21:56
  • @01d55 Thank you very much! I understood now. Now I revised my code. so there is no recursive callings. I wonder do I need to write anything in the destructor in order to free memory when I call delete function? – weeo Nov 26 '11 at 22:01
  • 1
    Now that you changed the code and the body of the question, the title is completely off... – jrok Nov 26 '11 at 23:15
  • You should learn about constructor initializer lists. The default constructor could be better written as `Graphnode() : state(), x(), depth() { }`. – Kerrek SB Nov 27 '11 at 00:32

1 Answers1

0

Your code will create an infinite loop when you try to create one Graphnode

You could try creating a specific constructor for the sub-Graphnodes so that within that constructor more Graphnode's are not created

DanZimm
  • 2,528
  • 2
  • 19
  • 27