Dynamic_cast

The syntax of dynamic cast:
dynamic_cast< Type* >(ptr)

This dynamic_cast will try to cast ptr to a pointer of type Type*. This cast is executed at runtime.let us try to compile

It will not compile, giving error
dynacas.cpp: In function ‘int main()’:
dynacas.cpp:15:39: error: cannot dynamic_cast ‘base’ (of type ‘class Base*’) to type ‘class Der*’ (source type is not polymorphic)
Der* der = dynamic_cast<Der*>(base); // OK
^
dynacas.cpp:18:35: error: cannot dynamic_cast ‘base1’ (of type ‘class Base*’) to type ‘class Der*’ (source type is not polymorphic)
der = dynamic_cast<Der*>(base1); //

Hence dynamic_cast works only for polymorphic classes. so to compile we have to make Class B polymorphic. Like Below

Note: (1) When dynamic_cast fails in case of casting pointer it returns NULL.

Here der = dynamic_cast<Der*>(base1); return NULL to der,as the cast is invalid because base1 is not pointing to Der class object. if we make base1, to point to der object then it will succeed.

(2) When dynamic_cast fails in case of casting reference it gives exception of std::bad_cast.

output:
bad casting: std::bad_cast




Related Contents to follow