Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward declaration issue

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 StatusEffects 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?

like image 256
Megatron Avatar asked Oct 27 '25 06:10

Megatron


1 Answers

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.

like image 116
sharptooth Avatar answered Oct 28 '25 19:10

sharptooth



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!