this question has answer here:
- what object slicing? 16 answers
i trying understand how dynamic_cast works. have class interfaceelement class menu derived it. in program, create no objects of class interfaceelement. when executing following code (executing line dynamic_cast, more precise), bad_cast exception thrown
void drawinterfaceelement(interfaceelement elem, int colour1, int colour2) { if (elem.gettype()=="menu") { menu &cur = dynamic_cast<menu&>(elem); this->drawmenu(&cur,colour1,colour2); } }
why?
take interfaceelement
reference. incur slicing taking value, causing menu
subobject lost. dynamic_cast
cannot cast type, causing std::bad_cast
thrown (if converting pointer, null pointer returned).
Comments
Post a Comment