How Vtable of Virtual functions work

后端 未结 3 1385
离开以前
离开以前 2021-01-13 17:58

I have a small doubt in Virtual Table, whenever compiler encounters the virtual functions in a class, it creates Vtable and places virtual functions address over there. It h

3条回答
  •  一整个雨季
    2021-01-13 18:21

    Each time you create a class that contains virtual functions, or you derive from a class that contains virtual functions, the compiler creates a unique VTABLE for that class.

    If you don’t override a function that was declared virtual in the base class, the compiler uses the address of the base-class version in the derived class.

    Then it places the VPTR into the class. There is only one VPTR for each object when using simple inheritance . The VPTR must be initialized to point to the starting address of the appropriate VTABLE. (This happens in the constructor.) Once the VPTR is initialized to the proper VTABLE, the object in effect “knows” what type it is. But this self-knowledge is worthless unless it is used at the point a virtual function is called. When you call a virtual function through a base class address (the situation when the compiler doesn’t have all the information necessary to perform early binding), something special happens. Instead of performing a typical function call, which is simply an assembly-language CALL to a particular address, the compiler generates different code to perform the function call.

提交回复
热议问题