Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Advanced
Jul 31, 1998

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.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date