0

I am very new to c++ and i am trying to define a Node class which holds information about another node, in this case the node will be the parent node so i can trace the most optimal route using an A* search.

so far i have tried (node.h file):

class node{

    private:
    int xCoord;
    int yCoord;
    int value;
    int hueristicCost;
    int pathCost;
    class node parent;

    public:
    node(int xC, int yC, int value);
    int getXPos();
    int getYPos();
    int getValue();


};

But this throws the compilation error:

node.h:10:13: error: field ‘parent’ has incomplete type

I am probably missing something stupidly obvious, but how would i go about completing this?

maxywb
  • 2,275
  • 1
  • 19
  • 25
chris edwards
  • 1,332
  • 4
  • 13
  • 31
  • 1
    It should probably be a pointer. Otherwise if you were able to instantiate one it would consume infinite memory. Also duplicate of http://stackoverflow.com/questions/2706129/can-a-c-class-include-itself-as-an-attribute – maxywb Mar 10 '14 at 16:56

3 Answers3

3

A member must be a complete type (as the error message oblivious already tells you). This means that you can´t have a forward declared member.

Notice, that you can already use node (as complete type) inside the node class.

However, defining a member of type node is still not possible, because this would lead to infinit recursion. Thus you probably want a node* if you have a tree-like model. Also notice that class Foo* member; is indeed possible. This is the usual solution if you really cant avoid forward declaration.

Sebastian Hoffmann
  • 11,127
  • 7
  • 49
  • 77
2

You can't declare an object of a class inside that class.

Possible duplicate: why can't we declare object of a class inside the same class?

Instead, you can define a pointer as others have mentioned:

node* parent
Community
  • 1
  • 1
brokenfoot
  • 11,083
  • 10
  • 59
  • 80
0

class node parent;

should be:

node parent;

or rather:

node* parent;
  • 1
    The class-key is optional; removing it won't make any difference. The second suggestion is (probably) correct, but simply stating it with no explanation doesn't really answer the question. – Mike Seymour Mar 10 '14 at 17:01