C++ What’s the standard way to define a recursive constructor?

A constructor only builds one thing, so you can’t use a constructor to build a group of things.

If you use new Class[ 20]; // 20 Classes get allocated, but each is constructed once in the constructor.

class Class
{
    Class * left;
    Class * right;
    Class(  SomeObject & x )
    {
         eatSomeData( x );
         left = nullptr;
         right = nullptr;
         if (x->buildleft() )
             left = new Class( x );
         if (x->buildright() )
             right = new Class( x );
    }
};

At each call to the constructor, the constructor only deals with the object it is creating, the fact it is doing this recursively (based on the data in x), is sort of different. In this case the class is heavily bound into the tree, and can’t be easily constructed without building a tree. Yes it is possible (from comments), but really really not advisable.

If you have a group of items you want to store (e.g. a tree), the typical building blocks are

  1. Item – the thing (object) you store in the tree.
  2. Node – an object which understands the tree, and how to traverse the tree.
  3. TreeContainer – an object which holds the top of the tree, and which knows how to find stored Items
  4. Builder – an object or function which takes your data and adds it into the tree by calling methods of the TreeContainer

Leave a Comment