Archived

This topic is now archived and is closed to further replies.

gimp

Determining type at runtime?

Recommended Posts

I have a factory that pumps out objects based on configurations loaded from a file. I have a case where I load a certain file and expect to recieve a certain object from the factory. How can I be sure I have the correct class? do I try a dynamic_cast and see if it trips an exception? crappy psudo: class CObject (Basetype). class CSurface : public CObject CObject* Obj = Factory(File); try{ CSurface* Surface = dynamic_cast(Obj); catch(bad cast){ //error in surface file! //Assume this now works Surface->GetType() Is that about right? Or is there a better way?

Share this post


Link to post
Share on other sites

CFileImage SurfaceFile(m_LightwaveObject.Tags.c_str());
CSurface* Surface = 0;
CObject* Object = XML::Load(SurfaceFile);
try
{
Surface = dynamic_cast(Object);
}
catch(bad_cast)
{
Log << "ERROR : Error in surface file. Incorrect object type." << Endl;
return;
}

a_Model.Surfaces[i] = Surface;

Actual code...

Share this post


Link to post
Share on other sites
according to msdn, dynamic_cast only throws the bad_cast exception when the target type is a reference. Otherwise, it simply returns the value 0 (or NULL) for a bad cast.

To account for this, you need to add
if(!Surface)
throw bad_cast;
after the dynamic cast

Share this post


Link to post
Share on other sites