I'm pretty new to C++ and I am working in a little roguelike game. I have a generic class named Actor
, which has 2 child classes, NPC
and Player
. The idea is for each child to contain specific data, such as experience provided by killing an NPC or the Player's stats, and special methods. On the other hand, Actor
contains general methods such as move, because both player and NPC should move.
Now I have a vector of NPC pointers
, and my move method should check if the target tile is occupied by an NPC (and some other NPC info), but I don't have access to that class from Actor
. I added a forward declaration to NPC
inside of Actor
, but then I get this error:
pointer to incomplete class type is not allowed
because forward declaration is not enough to access NPC
methods.
Actor.h:
class NPC; // Forward declaration.
class Actor
{
public:
void move(std::vector<std::unique_ptr<NPC>> & NPCs);
}
Actor.cpp:
void Actor::move(std::vector<std::unique_ptr<NPC>> & NPCs)
{
// Go through the NPCs.
for (const auto &NPC : NPCs)
{
if (NPC->getOutlook() > 0) ... // Error.
}
}
I could put the move method inside both NPC
and Player
, but I would be duplicating code, and that's a pretty bad idea.
What would be the best solution here? I guess there is a better way to organize this, but it seems pretty logical as it is. Maybe some kind of inheritance or virtual functions magic?
Thanks! :)
You will need to include the header where NPC is defined in Actor.cpp, otherwise the definition of NPC will be missing.
// Actor.cpp
#include "NPC.h"
void Actor::move(std::vector<std::unique_ptr<NPC>> & NPCs)
{
// Go through the NPCs.
for (const auto &NPC : NPCs)
{
if (NPC->getOutlook() > 0) ... // Now you'll be able to access this.
}
}