devxlogo

When dynamic_cast Fails

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 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.

See also  Is Machine Learning Automating Creativity in Graphic Design?
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist