Reputation: 2949
I have a cyclical redundancy circular dependency between two classes in my project, StatusEffect
and BaseCharacter
.
Both classes need to be aware of each other as the BaseCharacter
needs to store a set of StatusEffect
s and StatusEffect
needs to be able to do operations on BaseCharacter
. I don't think it's possible to eliminate this behavior and still have it work correctly. Here's what I'm trying to do right now:
Base Character exists inside the namespace Game::Character
and StatusEffect
exists inside the namespace Game::StatusEffects
inside StatusEffects.h, I forward declared BaseCharacter
like so:
namespace Game {
namespace Character {
class BaseCharacter;
}
}
then below it I have:
namespace Game
{
namespace StatusEffects
{
class StatusEffect
{
public:
virtual void TickCharacter(Game::Character::BaseCharacter* character, int ticks = 1)
{
std::cout << "Name " << character->GetName() << std::endl;
}
protected:
private:
std::string name;
int StatusEffectUID;
};
}
}
However, this is giving me a compiler error:
Error 1 error C2027: use of undefined type 'Game::Character::BaseCharacter'
I thought that because I'm using a pointer, this forward declaration is fine. Is there something else I need to forward declare? I dont need to forward declare the whole class definition do I?
Upvotes: 4
Views: 1981
Reputation: 39354
Your forward declaration
is fine. However, you must not refer to any of the members of such a class.
You should only declare the TickCharacter method in the header. You should then define
the StatusEffect::TickCharacter
method in its own module file after #include
ing the header file which contains the full declaration of BaseCharacter
.
Upvotes: 2
Reputation: 170479
You can't call a method through a pointer to a forward-declared class. You have to move this code somewhere where the class is already defined - for example into a .cpp file that includes both classes definition.
Upvotes: 9