Two separate classes that need each other

When you have two classes that need each other to work, but both can't be defined at the same time you can use forward declaration. When you declare some class in advance just to use it in other class problems can arise using this class' functions, since the declaration has not been compiled yet and the compiler does not know which functions are located and where. You end up with mutually exclusive #include statements that report error in their class because the previous wasn't defined yet.

This is a situation where you have to step back and think, whether this is the right design pattern. Many times it is not. If it is, do following:


// In class1.h : forward declaration
class class2;

class1
{
  // must be pointer because pointer
  // data type has same size no matter
  // what the object is
  class2* class2_p;
}

// In class1.cpp : if you include cpp file here than all class'
// functions would basically be declared twice

#include "class2.h"

void class1::some_function()
{
  // if it wasn't for the header include
  // this function would be impossible to
  // call because the compiler would not know
  // what to call
  class2_p->some_function();
}

// In class2.h : real declaration of class2
#include "class1.h"

class class2
{
  // declaration of member variable of type class1
  // is as usual, because it was declared before class2
  class1 class1_obj;
}

// In class2.cpp : include just class2 header file, class2
// header file is included there already
#include "class2.h"

void class2::some_function()
{
  // call function of class1 object as normal
  // because it was defined before all class2 declarations
  class1_obj.some_function();
}


Previous: Easy reference for implementing signal and slot
Next: Qt doesn't display Jpg and Gif files in release built on Windows