Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C++ compilers bitch when I do this

Name: Penis Moai 2006-08-12 16:58

Say I have two .cpp files and their corresponding .h files.  For the sake of brevity I'll leave it to just the parts that cause trouble:

==============================

//-------
//actor.h
//-------

#include "mapdef.h"

class Actor {
 ...
 private:
    Level *parent_level;
 ...
};
==========================

// ----------
// mapdef.h
// ----------
#include "actor.h"

class Level {
  ...etc etc...
 
  private:
     Actor *actors;   // I'd use a linked list, vector, or something more flexible in the actual code
...etc etc blah blah blah...
};

==========================================================

I also use #ifdef _ACTOR_H blah blah blah to make sure header files are never loaded more than once in the preprocessor (which causes compilation to terminate w/ error), like good programming practice.

Anyway, because of the way the preprocessor does things, this causes problems.  Say a .cpp file does an #include "mapdef.h".  The Level class refers to an Actor, and the mapdef.h itself #includes actor.h so it can "know" what an Actor is.

...but the compiler gets confused because then it looks in Actor class and it refers to a Level object... but Level isn't finished being defined yet.  Because these two classes refer to each other in some way for necessary objects/pointers/etc, the compiler shits.

I do find that adding "class" before objects fixes it:

class Actor {
  (blah blah blah)
  private:
     class Level *parent_level;
  (blah blah blah)
};

class Level {
  (blah blah blah)
  private:
     class Actor actors[200];
  (blah blah blah)
};

But I've never seen this done before in anyone else's code, and I'm not sure this is "kosher" by ANSI/ISO standards even though gcc and Visual C++ allow it.

The way I fix it... am I doing it right?  Or is there a better, less iffy way?

Name: Anonymous 2006-08-12 17:02

You can do it the way you did, or you could put some class Actor; and class Level; before the definition of the opposite classes. (I think I got the syntax right)

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List