8.2 How to Access Run-Time Class Information

If you have derived your class from CObject and used the DECLARE_DYNAMIC and IMPLEMENT_DYNAMIC macros explained previously, the CObject class has the ability to determine the exact class of an object at run-time. This ability is an extension of the normal capabilities of C++.

The ability to determine the class of an object at run-time is most useful when extra type checking of function arguments is needed and when you must write special-purpose code based on the class of an object.

The CObject member function IsKindOf can be used to determine if a particular object belongs to a specified class or if it is derived from a specific class. The argument to IsKindOf is a CRuntimeClass, which you can get by using the RUNTIME_CLASS macro with the name of the class. The use of the RUNTIME_CLASS macro is shown below.

·To use the RUNTIME_CLASS macro:

Use RUNTIME_CLASS with the name of the class, as shown here for the class CObject:

CRuntimeClass* pClass = RUNTIME_CLASS( CObject );

You will rarely need to access the run-time class object directly. A more common use is to pass the run-time class object to the IsKindOf function, as shown in the next section.

·To use the IsKindOf function:

IsKindOf will test an object to see if it belongs to a particular class. The following steps show how to use IsKindOf.

1.Make sure the class has run-time class support. That is, the class must have been derived from CObject and used the DECLARE_DYNAMIC and IMPLEMENT_DYNAMIC macros explained previously on pages 264-265. (Since serialization support requires run-time class support, the class may have been defined with the DECLARE_SERIAL and IMPLEMENT_SERIAL macros.)

2.Call the IsKindOf member function for objects of that class, using the RUNTIME_CLASS macro to generate the CRuntimeClass argument, as shown here:

// in .H file

class CPerson : public CObject

{

DECLARE_DYNAMIC( CPerson )

public:

CPerson(){};

// other declaration stuff left out...

};

// in .CPP file

IMPLEMENT_DYNAMIC( CPerson, CObject )

CObject* myObject = new CPerson;

if( myObject->IsKindOf( RUNTIME_CLASS( CPerson ) ) )

{

//if IsKindOf is true, then cast is alright

CPerson* myPerson = (CPerson*) myObject;

}

Note:

IsKindOf returns TRUE if the object is a member of the specified class or of a class derived from the specified class. It only works properly in single-inheritance hierarchies.