Determining object's class name at runtime
John Love-Jensen
eljay@adobe.com
Wed Feb 5 15:49:00 GMT 2003
Hi Reinhard,
>Is there a way (with gcc 3.2) to determine the class name of an object at
runtime?
Yes. Given your example:
class A;
class B : public A;
const type_info* tA = &typeid(*pA); // Get the type information.
cout << tA->name(); // Textual (probably mangled) CLASSNAME.
bool match = dynamic_cast<A*>(pA) != NULL; // Check ISKINDOF.
All these are explained in Section 15.4 of Stroustrup's C++PL (3rd ed or
Special ed).
If you find that you need to use these kinds of constructs a lot, you may
want to consider using a more appropriate language or reconsider your
applications design. It may be that you are not using the OO facilities as
much as you should. (If you need this mechanism for callbacks or passing
things through the OS API or across a C ABI, then that's apropos.)
Perl, Java, Lisp/Scheme/CLOS, Objective-C are all good choices.
--Eljay
More information about the Gcc-help
mailing list