Getting an Object's Class Name at Runtime

If you wanted only an object's class name, you'd have an easy time, assuming that all your classes were derived from a common base class, CObject. Here's how you'd 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 would override the virtual GetClassName function, which would return a static string. You would get an object's actual class name even if you used a CObject pointer to call GetClassName. If you needed the class name feature in many classes, you could 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.