Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Two classes needing each other

Tags:

c++

oop

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?

like image 894
Johannes Jensen Avatar asked Jul 06 '10 20:07

Johannes Jensen


2 Answers

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.

like image 87
Fred Larson Avatar answered Oct 22 '22 17:10

Fred Larson


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.

like image 5
Edwin Buck Avatar answered Oct 22 '22 19:10

Edwin Buck