I have roughly gone thro' the defination. But still I am in confusion as to how I can implement in C++. The example is as follows: // dynamic_cast #include <iostgream.h> #include <exception> // the header file I do not know class CBase{virtual void dummy() {} }; class CDerived: public CBase {int a;}; int main() { try { CBase *pba=new CBase; CDerived *pd; pd=dynamic_cast<CDerived* >(pba); if (pd==0) cout << "Null pointer on first type-cast" << endl; pd=dynamic_cast <CDerived* >(pbb); if (pd==0 cout << "Null pointer on second type-cast" <<endl; } catch (exception& e) {cout <<"Exception: " <<e.what();} return 0; }
Dynamic cast is a concept of Type conversions. It is used when we don’t know about type of object is. So at that time it performs type-safe downcasts where one of type is converting into some other types dynamically. It is used only with pointers objects and references to objects. Example of Dynamic cast if(JumpStm *j = dynamic_cast<JumpStm*>(&stm)) { ... } else if(ExprStm *e = dynamic_cast<ExprStm*>(&stm)) { ... } Hop this will give you some guideline.