Run-Time Class Information

The C++ language was designed for speed and efficiency; therefore, binding among functions and data elements is done at compile and link time. Even the implementation of virtual functions depends on a data structure (known as the v-table) that is set up during compilation. Other object-oriented languages, such as Smalltalk, are designed for flexibility. Their binding is done at run time; objects send and receive standard-format messages that are processed by an interpreted language.

The Microsoft Foundation classes offer the developer some optional features usually associated with a run-time–bound system. If you derive a class from CObject, you can use member functions to access, at run time, (1) the class name and (2) the classes above it in the derivation hierarchy. You can also retrieve class information for any CObject-derived class declared in your program. This information allows you to safely cast a generic CObject pointer to a derived class pointer.

Run-time class information is particularly valuable in the Debug environment because it can be used (1) to detect incorrect casts and (2) to produce object dumps with class names included.

Run-time class information is, of course, available in the Release environment. If in Windows, for example, you need to process the children of a frame window, you can use the frame's GetWindow member function to return a generic CWnd pointer for each child window. If you want to know the child's specific class, then you can use the CObject member functions IsKindOf or GetRuntimeClass. During serialization, the runtime class information is stored to the archive along with object data.

Run-time class testing is not meant to be a substitute for using virtual functions. Use the run-time type information only when virtual functions are not appropriate, as in the GetWindow example described above.

In order to access run-time type information, you must use the DECLARE_DYNAMIC or DECLARE_SERIAL macros in your class declaration, and you must use the IMPLEMENT_DYNAMIC or IMPLEMENT_SERIAL macros in your class implementation.