C++: How to look at vptr/ vtable contents

2.9k views Asked by At

Every C++ object that has a virtual function has a vptr that points to a vtable. How can I see what this vptr is, and the contents it is point to? I understand this is compiler dependent and it could put vptr anywhere in the object memory space. But is there anyway I can find what it is?

Cheers.

1

There are 1 answers

1
ssg On

In this specific case, C has one vtable and A and B have none. You can see this for yourself by out-of-lining C's member functions, so that the vtable will actually be emitted, and correcting the other compile errors: extern "C" int puts(const char *);

struct A { virtual void func_1() = 0; };
struct B { virtual void func_2() = 0; };

struct C : A, B
{
  void func_1();
  void func_2();
};

... compiling to an object file, and then looking at the symbols:

$ gcc -c test.cc
$ nm test.o | c++filt
                 U puts
0000000000000000 T C::func_1()
000000000000001a T C::func_2()
0000000000000033 T non-virtual thunk to C::func_2()
0000000000000000 V typeinfo for A
0000000000000000 V typeinfo for B
0000000000000000 V typeinfo for C
0000000000000000 V typeinfo name for A
0000000000000000 V typeinfo name for B
0000000000000000 V typeinfo name for C
0000000000000000 V vtable for C
                 U vtable for __cxxabiv1::__class_type_info
                 U vtable for __cxxabiv1::__vmi_class_type_info
    void C::func_1() { puts("func_1"); }
    void C::func_2() { puts("func_2"); }

By above steps you can find the content it points to.