tags:

views:

156

answers:

2

I'm making a game and I have a class called Man and a class called Block in their code they both need each other, but they're in seperate files. Is there a way to "predefine" a class? Like Objective-C's @class macro?

+11  A: 

Yes.

class Man;

This will declare Man as an "incomplete type". You can declare pointers or references to it and a few other things, but you can't create an instance or access members of it. This isn't a complete description of what you can and can't do with an incomplete type, but it's the general idea.

Fred Larson
Important to note, you can continue on and include the full type later and gain access. You might use incomplete types in the header then include the full header definition into the cpp to make use of it.
Greg Domjan
+4  A: 

It's called a circular dependency. In class Two.h

class One;

class Two {
  public:
    One* oneRef;
};

And in class One.h

class Two;

class One {
  public:
    Two* twoRef;
};

The "class One;" and "class Two;" directives allocate a class names "One" and "Two" respectively; but they don't define any other details beyond the name. Therefore you can create pointers the class, but you cannot include the whole class like so:

class One;

class Two : public One {
};

class Three {
  public:
    One one;
};

The reason the two examples above won't compile is because while the compiler knows there is a class One, it doesn't know what fields, methods, or virtual methods, class One might contain because only the name had been defined, not the actual class definition.

Edwin Buck