0

The below code should obviously not compile (Equivalent to defining a class as C { C myC }, which would take infinite memory). The question is how does C++ actually do the check?

class Node {
     vector<Node> mChildren{ Node }
}

When I try to compile, I get the following error.

trie.cpp:6:35: error: expected primary-expression before ‘}’ token
vector<Node> mChildren { Node };
                               ^
trie.cpp:6:35: error: could not convert ‘{<expression error>}’ from ‘<brace-enclosed initializer list>’ to ‘std::vector<Node>’

Is it because the class Node has yet to be fully declared? How come I can use it as a template argument to vector. A similar issue arises with

class C {
  C myC;
};
Benjy Kessler
  • 7,356
  • 6
  • 41
  • 69
user804649
  • 315
  • 2
  • 12
  • 1
    Your first version isn't equivalent to the C struct example at all. A `vector` doesn't contain a Node directly, only a pointer to an array of nodes. Your initialization makes no sense though. – Mat Apr 21 '15 at 18:35
  • 4
    In general you can't [place incomplete types in standard library containers](http://stackoverflow.com/q/18672135/241631). Your initialization is not syntactically correct though, you need this - `std::vector mChildren{ Node{} };` (you need a `Node` instance, not the type name, and there's a missing semicolon). If you do that replacement you'll start seeing errors about calling the default constructor before the class definition is complete. – Praetorian Apr 21 '15 at 18:43
  • You are missing a semicolon at the end of the Node class. – Benjy Kessler Apr 21 '15 at 18:50
  • Thanks Prateorian. I wish there was a way I could flag your comment as the answer. – user804649 Apr 21 '15 at 19:03

1 Answers1

1

You have two problems in you Node class. You are missing a semicolon at the end and you have a weird {Node} at the end of the line. Fix that and it will compile.

class Node {
  Node() {}
  vector<Node> mChildren= { Node() };
};

This compiles fine.

Benjy Kessler
  • 7,356
  • 6
  • 41
  • 69