Why vptr is not static?

前端 未结 7 892
忘了有多久
忘了有多久 2020-12-28 19:27

Every class which contains one or more virtual function has a Vtable associated with it. A void pointer called vptr points to that vtable. Every object of that class contain

相关标签:
7条回答
  • 2020-12-28 20:14

    The whole point of the vptr is because you don't know exactly which class an object has at runtime. If you knew that, then the virtual function call would be unnecessary. That is, in fact, what happens when you're not using virtual functions. But with virtual functions, if I have

    class Sub : Parent {};
    

    and a value of type Parent*, I don't know at runtime if this is really an object of type Parent or one of type Sub. The vptr lets me figure that out.

    0 讨论(0)
提交回复
热议问题