The dynamic_cast<> operator may convert an object to another related (derived or a base) object at run-time. When it fails to convert a pointer to the target pointer, it returns NULL:
Date date;string * p = dynamic_cast &date; //string and Date //are not related; cast failsif (p) { //...}else { //failure//...}
When it fails to convert an object reference to a reference of an object of the desired type, it throws an exception of type std::bad_cast:
try {string s = dynamic_cast (date); //will surely fail and //throw an exception}catch (std::bad_cast){}
So make sure to catch whenever you’re using reference cast and always check the returned value when using it for a pointer cast.