I\'m facing with the following design problem:
TL;TD need to determine if Hero(class) can use specific object while there\'s many heroes implementations
I have
You could use dynamic_cast<>()
to determine the type of your Hero pointer, like so:
Hero *h;
Weapon * i;
// do something assign values
if(dynamic_cast != nullptr)
h->use(i);
where HeroSubClass
is the particular subclass of Hero
that you want to check for (Warrior
, etc.). If your Hero *
is not a pointer to an object of class HeroSubClass
, dynamic_cast
will return nullptr
, if it is, it will return a HeroSubClass *
.
Alternatively, you could just check the type of the Weapon *
within use()
for each HeroSubClass, and perhaps print out something like "Warrior cannot use Staff" if it's an object of the wrong class.