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?