3

I am programming a small game in C++ as an exercise, and I've come across a conundrum. The basic idea is that a Level has a vector of Entity, and each Entity instance knows which level it belongs to. Pretty straightforward so far.

I was getting some nasty compile errors in my Entity class as it couldn't figure out what Level was. A simple forward class declaration right before the declaration of Entity easily fixed that. However, I am already including "Level.h" in "Entity.h". And Level and Entity are both declared and defined in the same namespace.

Note: Entity.h also includes Level.h.

#include "Level.h"

namespace GameNS {

  // Required, otherwise the compiler complains
  class Level;

  class Entity
  {
  public:
  ...

Shouldn't the compiler already know what Level is, by the time it reaches Entity?

Andrei Bârsan
  • 3,473
  • 2
  • 22
  • 46

1 Answers1

5

No, that's not how the C++ compiler works. What it does is it basically passes through the files one translation unit at a time. A TU is, loosely put, an implementation file with all its includes.

If you have include guards in Level.h and Entity.h (you probably do) and they include each other, one of them, depending on the order, will be left out by the compiler, and one of the names won't be declared.

As a rule of thumb, use forward-declarations when you can, and includes where you must.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • Ah, I see, thanks for the explanation! I find it interesting that you can make a file stop compiling simply by including it in a file it includes (this is exactly the process I went through when I ended up with this error). – Andrei Bârsan Mar 22 '13 at 13:20
  • @AndreiBârsan yeah, cpp is fun like that. – Luchian Grigore Mar 22 '13 at 13:26
  • Do you happen to know of a good book that explains these sort of things? Stuff like the C++ Primer don't say too much about the actual compilation process. Or should I just start poking around with g++'s source code? – Andrei Bârsan Mar 24 '13 at 10:24
  • 1
    @AndreiBârsan C++ is so complex, I doubt there's one book explaining everything, but http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list is a good start. – Luchian Grigore Mar 24 '13 at 10:59