Problems with passing objects in tree structure I'm new to C++ and arduino. I want to build an object Tree, but it did not behave like I expected. Here is the code:

TreeNode.h

class TreeNode {

  public:
    TreeNode(String inputNodeName);
    TreeNode *children[];
    TreeNode &amp;getChild(int index);
    int getLength();
    String nodeName;
    void addChild(TreeNode &amp;node);
    String getName();

  private:
    int childLength;
};


TreeNode.cpp

  TreeNode::TreeNode(String inputNodeName) {
    nodeName = inputNodeName;
    childLength = 0;
  }

  TreeNode &amp;TreeNode::getChild(int index) {
    return *children[index];
  }

  int TreeNode::getLength() {
    return childLength;
  }

  String TreeNode::getName(){
    return nodeName.c_str();
  }

  void TreeNode::addChild(TreeNode &amp;node) {
    children[childLength] = &amp;node;
    childLength++;
  }


I'm initialising it in the setup function:

void setup() {
    Serial.begin(9600);

    TreeNode mainTree("main");
    TreeNode firstChild("first child");
    TreeNode secondChild("second child");
    TreeNode subChild("subschild");

    Serial.println(mainTree.getName()); //prints "main"
    Serial.println(firstChild.getName()); //prints "first child";
    Serial.println(secondChild.getName()); //prints second child";

    mainTree.addChild(firstChild);
    mainTree.addChild(secondChild);
    Serial.println(mainTree.getName()); // prints an empty string
    Serial.println(secondChild.getName()); //prints second child"

    secondChild.addChild(subChild);
    Serial.println(secondChild.getName()); //prints an empty string
}


So my problem is, when I'm adding a child to a node, the node name is empty, or strange characters will be displayed.
I think I misunderstood passing an object by reference. Can anybody explain what I did wrong?
TreeNode *children[];


That declares an array of pointers however it also requires that you assign memory to it. I never see you allocate that memory.

If you only expect a small amount of children then you can use that upper bound as a static allocation:

#define MAX_CHILDREN 10

//...
TreeNode *children[MAX_CHILDREN];


Otherwise use a vector instead:

std::vector&lt;TreeNode *&gt; children;