Cyclic dependency between header files

In the headers, forward declare the member functions:

class Node
{
    Tree * tree_;
    int id_;

public:
    Node(Tree * tree, int id);
    ~Node();
    void hi();
};

In a separate .cpp file that includes all the required headers, define them:

#include "Tree.h"
#include "Node.h"

Node::Node(Tree * tree, int id) : tree_(tree), id_(id)
{
  tree_->incCnt();
}

Node::~Node() 
{
  tree_->decCnt();
}

etc

This also has the effect of keeping your headers readable, so it is easy to see a class’s interface at a glance.

Leave a Comment