Search code examples
c++virtualpointer-to-membermember-functionsvtable

Print address of virtual member function


I am trying to print the address of a virtual member function. If I know which class implements the function I can write:

print("address: %p", &A::func);

But I want to do something like this:

A *b = new B();

printf("address: %p", &b->func); 
printf("address: %p", &b->A::func);

However this does not compile. Is it possible to do something like this, perhaps looking up the address in the vtable at runtime?


Solution

  • Currently there is no standard way of doing this in C++ although the information must be available somewhere. Otherwise, how could the program call the function? However, GCC provides an extension that allows us to retrieve the address of a virtual function:

    void (A::*mfp)() = &A::func;
    printf("address: %p", (void*)(b->*mfp));
    

    ...assuming the member function has the prototype void func(). This can be pretty useful when you want to cache the address of a virtual function or use it in generated code. GCC will warn you about this construct unless you specify -Wno-pmf-conversions. It's unlikely that it works with any other compiler.