C++ – Mutually referencing classes

Some notes on defining classes that mutual references to instances of each other:

  1. The classes can’t hold the actual other class’s instance data, because that could potentially cause an infinite expansion memory allocation, so by definition, the classes should be defined to contain pointers to the instance of the other class.
  2. The classes C++ header files can’t be including each other (it will cause a compile error), because, this is literally telling the compiler to endlessly read the files, each one including the other.
    So only one class header can have an “include” statement pointing to the other.
  3. In order to successfully compile the class header file which doesn’t contain an “include” statement for the other class, a forward declaration of the other class is needed.
    I.E. a ‘ghost’ declaration of the class at the beginning of the file, just so the compiler ‘knows’ there is such an entity, and doesn’t throw an error.

Class A code:

#include "B.h"

class A
{
    B* TheB;
};

Class B code:

class A;

class B
{
    A* TheA;
};

Hope this was helpful!
If you find mistakes or inaccuracies in this post I’ll be very grateful of you share them with me in the comments.

Leave a Reply