Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: All
May 12, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

When dynamic_cast<> Fails

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 fails
if (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.
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date