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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With