I am building a simple game project for my project. I have the following classes:
class Character { public: virtual void Display(); virtual void SetParameters( char* param, ... ); }; class NonPlayableCharacter : public Character { public: virtual void Display(); virtual void SetParameters( char* paaram, ... ); int GetNPCState(); }
And then I have a bunch of classes that derive from either Character or NonPlayableCharacter. I define it like this:
std::vector<Character*> _allChar;
My problem is that at any given time I would like to perform some operation on one of the elements of the vector. Therefore, getting an element from a vector, I cannot directly call the GetNPCState() method, because the element in the vector is of type Character *. Thus:
_allChar[0]->GetNPCState();
does not work. So I tried to do this with the famous dynamic_cast:
NonPlayableCharacter* test = dynamic_cast<NonPlayableCharacter*>(_allChar[0]); test->GetNPCState();
The problem with this last attempt is that GetNPCState() fails because the object is null, and I know that the fact (via debugging) for _allChar [0] is not zero.
source share