Alex Rivera | Logout

How to determine if an object is an instance of certain derived C++ class from a pointer to a base class in GDB?

Asked 2011-12-16T01:59:45.690
66

I'm debugging a C++ program with GDB.

I have a pointer to an object of certain class. The pointer is declared to be of some super class which is extended by several sub-classes.

There is no fields in the object to specify the precise class type of this object but some virtual functions (e.g. bool is_xxx()) are defined to tell the class type at runtime.

Is there some way to tell the precise class type of an object in GDB without calling these virtual functions. Calling such functions in GDB may generate confusing result when the program is multi-threaded.

Edit
Report

2 Answers

74

Use ptype. If you use it by itself, you get the declared type of the pointer:

(gdb) ptype ptr
type = class SuperClass {
  // various members
} *

To get the actual type of the object pointed to, set the "print object" variable:

(gdb) set print object on
(gdb) ptype ptr
type = /* real type = DerivedClass * */
class SuperClass {
  // various members
} *
answered 2011-12-16T02:28:29.823
1

You do not need to call the virtual functions, you can just see the address of the virtual function or vtable. Another way is to use RTTI

answered 2011-12-16T02:08:47.910

Your Answer