Two Headers Using Each Other

One of my early frustrations ¬†was when I couldn’t make two headers include each other, but after a while, I actually figured out that you can ‘trick’ the compiler to do so! Heres how:

You have two headers, Mesh and Shader, and the Mesh uses some of Shader’s stuff, and Shader uses a reference of Mesh. In Mesh you include Shader.h, and use it from there, but in Shader.h, you don’t include Mesh.h, instead you make a Class Prototype so you can use the class name freely, and then in Mesh.cpp, you then include Mesh.h and do stuff with it. Now the code version:
Mesh.h

#include "Shader.h"

class Mesh
{
    void Create(ShaderProperty *a);
};

Mesh.cpp

#include "Mesh.h"

Mesh::Create(ShaderProperty *a)
{
 ...
}

Shader.h

class Mesh;
class Shader
{
 Mesh* stored;

 void SetStored(Mesh* ref);
}

Shader.cpp

#include "Shader.h"

#include "Mesh.h"

Shader::SetStored(Mesh* ref)
{
 stored = ref;
 stored.foo(10);
}

I just though I would share this tip to you guys, as it could become useful!

Advertisements