dynamic_cast<type> (expr):
The dynamic_cast performs a runtime cast that verifies the validity of the cast. If the cast cannot be made, the cast fails and the expression evaluates to null. A dynamic_cast performs casts on polymorphic types and can cast a A* pointer into a B* pointer only if the object being pointed to actually is a B object
Syntax:
1 |
dynamic_cast <new_type>(Expression) |
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
#include<iostream> using namespace std; class ClassA { public: virtual void display()const { cout << "This is from ClassA\n"; } }; class ClassB { public: virtual void display()const { cout << "This is from ClassB\n"; } }; class ClassC: public ClassA, public ClassB { public: void display()const { cout << "This is from ClassC\n"; } }; int main(){ ClassA* x = new ClassA; ClassB* y = new ClassB; ClassC* z = new ClassC; x -> display(); y -> display(); z -> display(); y = dynamic_cast< ClassB*>(x); //This cast will be fail if (y) y->display(); else cout << "No ClassB\n"; x = z; x -> display(); //Displaying from ClassC y = dynamic_cast< ClassB*>(x); // There will be Successful casting done here if (y) y -> display(); else cout << "No Class B\n"; } |
Output:
1 2 3 4 5 6 |
This is from ClassA This is from ClassB This is from ClassC no ClassB This is from ClassC This is from ClassC |
Recommended Tutorials: