Reputation: 4480
my dizzyCreature
class inherits from both a creature
class and a dizzy
class. It is also part of a polymorphic collection of creature
classes. If I know that my object in the creature
class is a dizzyCreature
, is there a way to call a function from the dizzy
class?
I have tried
creature[2].dizzyCreature::someFunction();
and
dizzyCreature::creature[2].someFunction();
and neither works. Any ideas?
Upvotes: 0
Views: 359
Reputation: 2590
You need to first check if the class is of the correct type, then cast it using dynamic_cast
, as has already been suggested. This solution is elegant since the dynamic cast itself does the type-checking - i.e. it will return NULL if you try to make an invalid cast. (There is no need to use typeid
)
As a side note, if I were you, I'd attempt to do whatever it is you're trying to do without multiple inheritance if possible. Multiple inheritance can open up a whole can of worms and is best avoided unless there is no other alternative.
Upvotes: 0
Reputation: 73433
If I understand correctly what you have is something like this: list<Creature*>
. This list contains some dizzyCreature
instances. On those instances you want to call methods of dizzy
class. If this is the objective then you can use dynamic_cast
to achieve this. Lets say you have Create* pCreature
then you can do:
dizzyCreature* pDizzyCreature = dynamic_cast<dizzyCreature*>(pCreature);
if(pDizzyCreature )
{
pDizzyCreature->someDizzyClassMethod();
}
Upvotes: 3