Search code examples
c++derived-classforward-declaration

C++ forward declarations with multiple classes, derived class


Currently I have 3 classes, set up like this:

World.h

include "WorldObject.h"
class WorldObject;
class TextObject; // when this is added, compiles fine, but tobj is incomplete when accessed 
//(world->tobj->function()).  if #include "TextObject.h" is added, numerous errors occur within TextObject.h
class World { 
public:
      WorldObject* wobj; // works fine
      TextObject* tobj; //trying to get this to be functional
};

WorldObject.h

#include "World.h"
class World;
class WorldObject {
public:
      WorldObject(World* world){...} // works fine, world can be accessed from world objects
};

TextObject.h

#include "WorldObject.h"
#include "World.h"
class TextObject : WorldObject {
public:
      TextObject(World* world) : WorldObject(w){...};
};

How can I use forward declaration so that tobj will be accessible from World.h, as obj is, with no errors? I am also using #pragma once at the beginning of each class. I have attempted to add "class World" to TextObject.h and "class TextObject" to World.h, but none of the seemingly standard procedures are working. Any suggestions?


Solution

  • #include <WorldObject.h> in your .cpp file rather than your header and you can access it from there.

    Your header includes are causing circular dependencies, which you avoid through forward declarations.