Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ classes refer to each other ( => error + field '...' has incomplete type)

Tags:

c++

class

Classes in my application work like this: Creature has few fields with Actions. When these Actions must be run Creature calls someActionField->do(this). Action has method viod do(Creature* cr) and all information about what to do with this Creature.

So, Creature must have Action field and know that Action has do method. Action must know that Creature has such fields like: Will, HP, etc...

I've got

creature.h

 #include "effect.h"
 #include "heedupdate.h"

 namespace Core
 {

 class Action;

 class Creature : public NeedUpDate
 {
 public:
     virtual ~Creature();
     int HP;
     Action onHit;
     Action onDie;
// ...


 };

 }
#endif

And action.h

#include "creature.h"

namespace Core
{


class Action
{
public:
Action();
virtual void _do(Creature* cr);
virtual ~Action();
};

But in this case field `onDie' has incomplete type error appears. If I include action.h into creature.h - I use files 'before each other'.

like image 911
Ben Usman Avatar asked Dec 05 '22 21:12

Ben Usman


1 Answers

You Creature class has members of type Action. The compiler needs to know the full definition of the Action class to compile that - an incomplete type as produced with a forward declaration is not enough.

The Action class only requires a pointer to a Creature object in that header. In that case, the compiler only needs to know that Creature will be defined at some point.

In your specific case, you could get away with inverting the order in which you declare your classes.

(i.e. forward-declare Creature in action.h, and include action.h in creature.h)

like image 70
Mat Avatar answered May 24 '23 00:05

Mat