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 }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: