When I run this code, i get the error: "Field 'children' has incomplete type 'Node[0]'". I'm coding in C++ and I want to create a Node class which creates in itself two other Node objects and so on, until it reaches the maxDepth. The full error I get:
18:24:16 **** Incremental Build of configuration Debug for project Tests ****
make all
Building file: ../main.cpp
Invoking: Cross G++ Compiler
g++ -std=c++0x -O3 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"main.d" -MT"main.d" -o "main.o" "../main.cpp"
../main.cpp:22:17: error: field ‘children’ has incomplete type ‘Node [2]’
Node children[2];
^
../main.cpp:8:7: note: definition of ‘class Node’ is not complete until the closing brace
class Node {
^
make: *** [main.o] Error 1
subdir.mk:18: recipe for target 'main.o' failed
And the code:
#include <iostream>
using namespace std;
class Node {
public:
int depth;
bool value;
Node(bool value, int depth, int maxDepth) {
this->value = value;
this->depth = depth;
if (this->depth < maxDepth) {
children[2] = {Node(false, this->depth + 1, maxDepth), Node(true, this->depth + 1, maxDepth)};
}
}
private:
Node children[2];
};
int main() {
Node tree(false, 0, 1);
return 0;
}
The real problem is that "Node" is undefined at the time "Node children[2];" is encountered by the compiler. You can have a pointer to it, but can't have an instantiation of it until it is fully defined (upon reaching the closing "}" ).
You have defined class
Node
to contain an array ofNode
objects:A
Node
cannot contain anotherNode
, because it must have a fixed size that is large enough to contain its members. It can contain pointers to otherNode
objects, and that's probably what you should use in this case:This means that you must re-write your assignment to the
children
array (which as it stands is incorrect anyway), so that it assigns values of typeNode *
: