Determining type at runtime?
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?
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 = Surface;<br> </pre> <br>Actual code… </i>
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
To account for this, you need to add
if(!Surface)
throw bad_cast;
after the dynamic cast
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement