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
Language: C++
Expertise: Advanced
Jul 31, 1998



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

Prefer dynamic_cast<> to typeid()

A robust, long lasting OO design relies on the premise that an existing class can be re-used in the future by means of derivation. Therefore, examining the actual type of an object with typeid() results in a code which is less flexible, since it cannot handle derived objects:
void Registry::Register (const Window& wind) //has to receive a Window object exclusively
if (typeid(wind) == typeid(Window)) //inflexible; objects derived from Window will fail this test
Store ( wind.GetHandle() );
	else //object derived from Window was received; not handled
cout<< "Window object expected!"<<endl;
The use of dynamic_cast <> rather than typeid() is a better choice - it will enable the Registry::Register() member function to cope with a Window object as well as any object derived from it:
void Registry::Register (const Window& wind) //has to receive a Window object exclusively
Window w=dynamic_cast<Window&>> (wind)  //will succeed even with derived objects
Store ( w.GetHandle() ); //it is guaranteed that Window::GetHandle() is called 
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