C++: Two classes needing each other

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?

Answers


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.


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.


Need Your Help

how to animate 2 different html elements with jquery concurrently?

jquery html jquery-animate move

I need to create a slide effect for 2 different html elements, but this animation must run concurrently.

Objective C: What's the easiest way to determine if a substring exists within an NSString?

objective-c

In PHP (which is what I'm most familiar with) it's a one line expression: