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:


class TreeNode {

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

    int childLength;


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

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

  int TreeNode::getLength() {
    return childLength;

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

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

I'm initialising it in the setup function:

void setup() {

    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";

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

    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?

  • 1
    Arrays do not expand like in Java or Basic. You need to allocate a specific number of entries, or use a linked list or C++ STL wrapper object like vector. – Majenko Jul 2 '18 at 9:26
  • Here we go - I have just drafted a blog entry on C arrays: majenko.co.uk/blog/arrays-pointers-what-c – Majenko Jul 2 '18 at 12:51
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<TreeNode *> children;

Not the answer you're looking for? Browse other questions tagged or ask your own question.