Pointers to virtual member functions. How does it work?

前端 未结 3 895
無奈伤痛
無奈伤痛 2020-12-03 07:12

Consider the following C++ code:

class A
{
public:
      virtual void f()=0;
};


int main()
{
     void (A::*f)()=&A::f;
}

If I\'d hav

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 07:42

    I'm not entirely certain, but I think it's just regular polymorphic behavior. I think that &A::f actually means the address of the function pointer in the class's vtable, and that's why you aren't getting a compiler error. The space in the vtable is still allocated, and that is the location you are actually getting back.

    This makes sense because derived classes essentially overwrite these values with pointers to their functions. This is why (a->*f)() works in your second example - f is referencing the vtable that is implemented in the derived class.

提交回复
热议问题