Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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