0

I have such a piece of code:

struct X
{
    virtual void f(){}
    virtual void g(){}
    virtual void h(){}
};
int main()
{
    auto p = &X::f, q = &X::g, r = &X::h;
    X *x = new X;
    return 0;
}

I thought the pointer to a virtual function would save the offset of the function in its' vtable. But when I use gdb to look at it, I found that the pointer value has nothing to do with the actual address of the function:

value of pointers

address of virtual functions

So, what's the actual meaning of the pointers? I know that a pointer to a virtual function, its actual pointing depends on the actual resolution of the virtual function. But my confusion is - if the value of the pointer to a virtual function does NOT represent the offset in the vtable, then what does it represent? And how does the program get the actual function by the value?

zclll
  • 77
  • 7
  • `auto p = X::f, q = X::g, r = X::h;` is not valid syntax. To get a member pointer you must always use `&`: `auto p = &X::f, q = &X::g, r = &X::h;`. If the compiler allowed the original code, that is only by a compiler-specific language extension. I would recommend compiling with `-pedantic-errors`, so that you don't accidentally use any non-standard language extension and get confused later when you switch to another compiler. – user17732522 Jun 04 '22 at 16:25
  • How did you even get this code to compile? What flags did you use? – Brian Bi Jun 04 '22 at 17:43
  • FYI, your inclusion of `bits/stdc++.h` is overkill since your example doesn't need any include files. Also, `bits/stdc++.h` is not a standard header file; not all compilers will accept it. – Thomas Matthews Jun 04 '22 at 18:13

0 Answers0