Cross referencing headers?

Started by
2 comments, last by brx 12 years, 11 months ago
I have a class header which contains a reference to another class header which in turn contains a reference to the first class header... And we arrive at a problem with sequenciality...

Anyway, here's my code for the first header:


#ifndef SceneClassDefined
#define SceneClassDefined

#include "D3DSysClass.h"
#include "GPUConstantBufferClass.h"
#include "SphereClass.h"

struct SceneInfoStruct
{
float MaxViewDistance;
int NumObjectTypes;
int NumSpheres;
float Filler1;
};

class SceneClass
{
public:

SceneClass(SceneInfoStruct * pSceneInfoPassed, D3DSysClass * pD3DSysPassed);
~SceneClass();

void AddSphere(SphereInfoStruct * pSphereInfo);

private:

SceneInfoStruct * pSceneInfo;
GPUConstantBufferClass * pSceneInfoBuff;
D3DSysClass * pD3DSys;
std::vector<SphereInfoStruct> * pSpheres;
};

#endif //SceneClassDefined


And here is the code for the second shader:


#ifndef SphereClassDefined
#define SphereClassDefined

#include "SceneClass.h"

struct SphereInfoStruct
{
float Center[3];
float Radius;
};

class SphereClass
{
public:

SphereClass(SphereInfoStruct * pSphereInfoPassed, SceneClass *pScenePassed);

private:

SphereInfoStruct * pSphereInfo;
SceneClass * pScene;
};

#endif //SphereClassDefined


The issue is that every time I create a Sphere I want its constructor to automatically call Scene::AddSphere() , but sequentiality of definition makes my solution impossible. How would you implement this? I assume there's a standard way of dealing with this kind of thing?
Advertisement
Hmm, I think in this particular instance I could move the definition of SphereInfoStruct into the SceneClass header and be OK...
Some search terms are "forward declaration" and "cyclic dependency"

To solve this via forward declarations, replace [font="Courier New"]#include "SphereClass.h[/font]" with [font="Courier New"]struct SphereInfoStruct;[/font] and replace [font="Courier New"]#include "SceneClass.h"[/font] with [font="Courier New"]class SceneClass;[/font]. Then add those [font="Courier New"]#include[/font]'s to your CPP files instead.
Use forward declarations.

In your code, the SphereClass header does not need the full definition of SceneClass since you only use pointers to SceneClass. Just replace the line

#include "SceneClass.h"

with

class SceneClass;


and move the include to the cpp file and you should be fine.

Note that in your case it would not work the other way around, because the SceneClass header actually uses the SphereInfoStruct as a template parameter of the vector.

This topic is closed to new replies.

Advertisement