Getting an Object's Class Name at Run Time
If you want only an object's class name, you'll have an easy time, assuming that all your classes are derived from a common base class, CObject. (Note that this example does not use the real MFC CObject class.) Here's how you get the class name:
class CObject
{
public:
virtual char* GetClassName() const { return NULL; }
};
class CMyClass : public CObject
{
public:
static char s_lpszClassName[];
virtual char* GetClassName() const { return s_lpszClassName; }
};
char CMyClass::s_szClassName[] = "CMyClass";
Each derived class overrides the virtual GetClassName function, which returns a static string. You get an object's actual class name even if you use a CObject pointer to call GetClassName. If you need the class name feature in many classes, you can save yourself some work by writing macros. A DECLARE_CLASSNAME macro might insert the static data member and the GetClassName function in the class declaration, and an IMPLEMENT_CLASSNAME macro might define the class name string in the implementation file.