c++ - Calling an object-specific function on a STL vector of polymorphic objects -


so have class hierarchy has entity class parent abstract class , bunch of other classes derive it, such door, player, ground, etc.

i have three-dimensional vector stores pointers objects of type entity , fill vector derived objects. within door class have method called isopen() returns bool. function specific door class , neither found in entity class nor in other derivations of (as don't need check whether, example, ground object open or not).

now, knowing there exists object of type door @ vector position i, j, k, call method isopen so: vector[i][j][k]->isopen(). unfortunately, when this, compiler returns class entity has no member named isopen(). understandable since function isopen() exclusive door class, can in order make sort of call possible?

one way solve down cast door * first. however, in order down cast type safe, should use dynamic_cast<door *>(). if entity not have virtual method, can add virtual destructor.

class entity {     //...     virtual ~entity () {} };  void foo (entity *e) {     //...     door *door = dynamic_cast<door *>(e);     if (door) {         if (door->isopen()) {             //...         }     }     //... } 

Comments

Popular posts from this blog

java - JavaFX 2 slider labelFormatter not being used -

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -