Search code examples
c++header-filescircular-reference

How to Resolve Circular Reference in Header File


I have the following header file (simplified for illustration here):

#include <vector>
class Box;
class Item {
  int row;
  int column;
  Box *box;
public:
  Item(Box *b) : box(b) {}
  void thiswontcompile() { box->dosomething(); }
  void foo();
};
class Box {
  std::vector<Item*> items;
public:
  Box() {}
  void addsquare(Item *sq) { items.push_back(sq); }
  void bar() { for (int i=0; i<items.size(); i++) items[i]->foo(); }
  void dosomething();
};

The compiler objects to the line with thiswontcompile(), complaining about an invalid use of the incomplete type 'class Box'. I know I can correct the error by moving this definition to the implementation file, but is there any way to keep all of this coding in the header file?


Solution

  • You can move the definition of thiswontcompile to the end of the header file, you just need to make the function inline.

    #include <vector>
    class Box;
    class Item {
      int row;
      int column;
      Box *box;
    public:
      Item(Box *b) : box(b) {}
      void thiswontcompile();
      void foo();
    };
    class Box {
      std::vector<Item*> items;
    public:
      Box() {}
      void addsquare(Item *sq) { items.push_back(sq); }
      void bar() { for (int i=0; i<items.size(); i++) items[i]->foo(); }
      void dosomething();
    };
    
    inline void Item::thiswontcompile() { box->dosomething(); }