Prefer dynamic_cast<> to typeid()

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!"<

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> (wind)  //will succeed even with derived objects{Store ( w.GetHandle() ); //it is guaranteed that Window::GetHandle() is called }}
See also  5 Benefits of Using Time Tracking Software

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