3

Attempting to create as simple parent/child node class but running into Incomplete Type Is Not Allowed error. Why?

class Node {
public:
    Node ParentNode;  //Error on this line
    string NodeName;


    Node(Node *node) : ParentNode(*node) {

    }
};
001
  • 13,291
  • 5
  • 35
  • 66
user3745593
  • 41
  • 1
  • 1
  • 4
  • 3
    If it was allowed then you got an infinite compilation. The compiler will try recursively to insert the definition of Node for each its instance.:) – Vlad from Moscow Dec 12 '17 at 20:39
  • You can make it a pointer. – 001 Dec 12 '17 at 20:40
  • 1
    `Node ParentNode;` => `Node *ParentNode;` ? – Stargateur Dec 12 '17 at 20:40
  • What's the size of a `Node`? Ignoring padding, it's the size of a `Node` + the size of a `string`. See how that doesn't really make sense? – Kevin Dec 12 '17 at 20:41
  • 2
    Possible duplicate of [Can a c++ class include itself as an attribute?](https://stackoverflow.com/questions/2706129/can-a-c-class-include-itself-as-an-attribute) – Kevin Dec 12 '17 at 20:43

2 Answers2

6

You are trying:

Node ParentNode;  //Error on this line

but Node is not a complete type at this point (you are in fact defining it at this point), a structure cannot contain an instance of itself, it can contain a pointer or reference to an instance of itself but not an actual instance. After all, if such recursive containment were allowed, where would it end?

Błażej Michalik
  • 4,474
  • 40
  • 55
SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23
3

The error hints at the fact that the definition of a class is incomplete while the class is being defined.

An object can't contain an instance of its own type – it would be infinitely large.

You want

Node* ParentNode;

and

Node(Node *node) : ParentNode(node)
molbdnilo
  • 64,751
  • 3
  • 43
  • 82