开发者

Polymorphism makes function inaccessible

开发者 https://www.devze.com 2023-03-02 15:52 出处:网络
I have a map of Sho开发者_如何转开发pables which has things in it that were initialised like this:

I have a map of Sho开发者_如何转开发pables which has things in it that were initialised like this:

Shopable* something = new Consumable();

Consumable has a function Heal, but Shopable doesn't. I need the map to stay as a Shopable map for some function parameter, but when I try and do:

consumables[itemName]->Heal(this);

in another function, it says "Class 'Shopable' has no member 'Heal'".

How can I get around this?


Either dynamic_cast, or create a virtual dummy Heal under Shopable.

Consumable *con = dynamic_cast<Consumable*>(consumables[itemName]);
if(con)
    con->Heal();
//else this shopable is not really a consumable

Alternatively, create a virtual function called Heal() under Shopable, with nothing in it. Or with a debugger warning in it (like assert(0)), so that you know if it's called by accident. Or make a pure virtual (virtual void Heal() = 0;), then your prorgam will crash if it's called.


Polymorphism only allows virtual dispatch of virtual functions that exist in the base class. You cannot call a function on a base class that does not exist in the base class, just because it might exist in the derived class.

In addition, you should really mean Shoppable* something = new Consumable(); unless Shoppable itself is just a typedef for some pointer type.


Is Heal something that every Shoppable should be able to do? If so, you should declare it as a pure virtual function in Shoppable and implement it in all subclasses.


Make Heal() a pure virtual on Shopable?


If Heal() does only apply to a specific class that was derived from Consumable then you should go with Alekseyev's solution of using dynamic_cast.

You will need to enable RTTI if it's not yet enabled and for performance critical code dynamic_cast can have a negative impact.

You might want to have a look at this site which explains the basics of RTTI in C++.

0

精彩评论

暂无评论...
验证码 换一张
取 消