Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Forward class definition required to compile some code

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?

like image 240
Andrei Bârsan Avatar asked May 09 '26 15:05

Andrei Bârsan


1 Answers

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.

like image 84
Luchian Grigore Avatar answered May 11 '26 05:05

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!