Tim Orton
Tim Orton

Reputation: 338

One class uses a second class which uses a struct defined in the first

I'm trying to make a model with bones. It loads a .obj file to create the mesh, and uses groups of faces to define each "bone" or part of the model.

I have a Model class. In the header file, I have defined a public struct called Vertex, which stores data such as the position and normal direction for each vertex in the model.

I also have a Bone class, which has vector (#include < vector >) of pointers to the Vertex struct, which looks like this:
std::vector< Model::Vertex* > vertices;

The Model class will have bones in it, so I have #included Bone in the header Likewise, the Bone class needs to know what Vertex is, so I have #included Model in its header.
This gives a type redefinition error for Bone, so I have put #pragma once at the top of the Bone header, but now my problem is this I get four compile errors relating to the line of code shown above.
The first two are: error C2653: 'Model' : is not a class or namespace name
The second two are: error C2065: 'Vertex' : undeclared identifier

However I'm sure there is nothing syntactically wrong with that line of code. And if I don't #include Bone in the Model class, it works perfectly fine.

Does anybody know how to resolve this type of problem? And/or is there a better way to do this?

EDIT: I have put class Bone; in the header of Model for forward decleration, but in the private: section of the Model header, I have Bone forearm; which gives an error that forearm uses an undefined class 'Bone'.
I'm not sure if I can reverse the order of the classes such as: http://www.parashift.com/c%2B%2B-faq-lite/misc-technical-issues.html#faq-39.14, because the Bone wants a pointer to Model::Vertex, not Model itself.

Upvotes: 0

Views: 114

Answers (1)

Mahesh
Mahesh

Reputation: 34625

I have put class Bone; in the header of Model for forward declaration, but in the private: section of the Model header, I have Bone forearm; which gives an error that forearm uses an undefined class 'Bone'.

Usually forward declarations are used for pointer/reference types. forearm is of Bone type. So, for forearm to instantiate, it should see the complete class definition of Bone. Forward declaration isn't just sufficient.

// Model.h
class Bone;  // Forward declaration
class Model{
    Bone *forearm; // or Bone& forearm;
    // .....
};

// Model.cpp
#include "Bone.h"
#include "Model.h" // This inclusion order doesn't matter.

// ....

Or you always make sure that Bone.h is included before Model.h, in every source file that includes Model.h. In that way, the compiler look forward approach won't fail.

Upvotes: 1

Related Questions