简体   繁体   中英

multiple inheritance and polymorphism

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?

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();
}

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 - ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM