title: Cyclic dependency between header files
body: <p>I'm trying to implement a tree-like structure with two classes: <code>Tree</code> and <code>Node</code>. The problem is that from each class I want to call a function of the other class, so simple forward declarations are not enough.</p>
  
  <p>Let's see an example:</p>
  
  <p><strong>Tree.h:</strong></p>
  
  <pre><code>#ifndef TREE_20100118
  #define TREE_20100118
  
  #include &lt;vector&gt;
  #include "Node.h"
  
  class Tree
  {
      int counter_;
      std::vector&lt;Node&gt; nodes_;
  
  public:
  
      Tree() : counter_(0) {}
  
      void start() {
          for (int i=0; i&lt;3; ++i) {
              Node node(this, i);
              this-&gt;nodes_.push_back(node);
          }
          nodes_[0].hi();    // calling a function of Node
      }
  
      void incCnt() {
          ++counter_;
      }
  
      void decCnt() {
          --counter_;
      }
  
  };
  
  #endif /* TREE_20100118 */
  </code></pre>
  
  <p><strong>Node.h:</strong></p>
  
  <pre><code>#ifndef NODE_20100118
  #define NODE_20100118
  
  #include &lt;iostream&gt;
  //#include "Tree.h"
  
  class Tree;    // compile error without this
  
  class Node
  {
      Tree * tree_;
      int id_;
  
  public:
  
      Node(Tree * tree, int id) : tree_(tree), id_(id)
      {
  //      tree_-&gt;incCnt();    // trying to call a function of Tree
      }
  
      ~Node() {
  //      tree_-&gt;decCnt();    // problem here and in the constructor
      }
  
      void hi() {
          std::cout &lt;&lt; "hi (" &lt;&lt; id_ &lt;&lt; ")" &lt;&lt; endl;
      }
  
  };
  
  #endif /* NODE_20100118 */
  </code></pre>
  
  <p><strong>Calling Tree:</strong></p>
  
  <pre><code>#include "Tree.h"
  ...
  Tree t;
  t.start();
  </code></pre>
  
  <p>This is just a simple example to illustrate the problem. So what I want is calling a function of <code>Tree</code> from a <code>Node</code> object.</p>
  
  <p><strong>Update #1:</strong> Thanks for the answers. I tried to solve the problem like in Java, i.e. using just one file per class. It seems I will have to start separating .cpp and .h files...</p>
  
  <p><strong>Update #2:</strong> Below, following the hints, I pasted the complete solution too. Thanks, problem solved.</p>