Operator dynamic_cast is used in RTTI.It cast a derieved class object into base class and vice versa at run time.
base b1;
derived d1;
if(b1 == dynamic_cast <base> (d1))
.....................
else
..................
RTTI stands for the Run Time Type Identification.
Generally Non Polymorphic Languages like C does not need RTTI. But in case of C++ it is needed because of Late binding associated decisions.
typeid is the operator used for identifying the type of object stored in the pointer.
Below example clears the point of used RTTI.
class Mammal { public: virtual bool lays_eggs() { return false; } // Mammal is polymorphic // ... }; class Cat: public Mammal { public: // ... }; class Platypus: public Mammal { public: bool lays_eggs() { return true; } // ... }; class Dog: public Mammal { public: // ... };
// A factory for objects derived from Mammal. Mammal *factory() { switch(rand() % 3 ) { case 0: return new Dog; case 1: return new Cat; case 2: return new Platypus; } return 0; }
int main() { Mammal *ptr; // pointer to base class int i; int c=0, d=0, p=0;
// generate and count objects for(i=0; i<10; i++) { ptr = factory(); // generate an object
cout << "Object is " << typeid(*ptr).name(); cout << endl;