1

I'm trying to implement an RB-Tree, in my tree each node has also a pointer to an other RB-Tree. My code looks like this:

class node{
    tree* subTree;
    . . . //some code goes here      
   node(){
      subTree = new tree; //error here !!
   }
};


class tree{
  . . . //some code
};

the problem is that since node is defined before tree, The compiler gives me No appropriate default constructor available. And If I move the node class after the tree class then again the same problem would happen with the constructor of node. What should I do?

MoNo
  • 307
  • 4
  • 15

1 Answers1

2

Forward declare class tree, then use only a constructor declaration in class node,

class tree; // forward declaration, allows node to contain incomplete tree types

class node
{
    tree* subTree;
public:
    //some code goes here      
    node(); // only the declaration
};

and finally define the node's constructor outside the class, but after the full definition of class tree,

class tree 
{ 
    // implementation 
};

node::node()
{
    subTree = new tree; // no more error here !!
}

Live example on Coliru The trick here is that a class can contain incomplete types (i.e. types for which only a declaration is available, but not the full definition), whenever you use them as pointers/references and do not need to compute/use their size. So, you can forward declare tree before class node, then declare the pointer tree* subtree in your class node and only declare the constructor. You then define the constructor after class tree is fully defined, since in the constructor you need the size of tree because of the subTree = new tree; statement. But you are now ok, since the class tree is fully available, and the constructor can be defined without problems. Hope this makes sense.

Related: When can I use a forward declaration?

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • @MoNo do a `make clean` before, clear all your previously build object files. If you use an IDE, there should be some option to clean the build. Also make sure your `node` class doesn't use incomplete types whenever it needs full definitions. If there are `node` member functions that need the full definition of `tree`, then define them outside the class `node`, after the definition of the class `tree`. – vsoftco Jun 02 '15 at 05:41