当基类中含有虚函数时, 编译器会自动进行以下的动作:
1、为每一个类增加一个VTABLE, VTABLE里记录了各各类里面, 所有在类或基类内声明为virtual的成员函数地址(代码所在地址)。
2、对基类和每个派生类都加入一个VPTR,并对所有这些类所定义对象内的VPTR进行初始化操作:使VPTR指向正确的VTABLE的第一个字段; VPTR是位于对象层次上的概念,当他指向了一个VTABLE时, 就知道自己是什么类型了。。
3、对每一个虚函数调用,都加入专用的虚函数代码,获取正确的函数地址。
the typical compiler creates a single table (called the VTABLE) for each class that contains virtual functions. The compiler places the addresses of the virtual functions for that particular class in the VTABLE. In each class with virtual functions, it secretly places a pointer, called the vpointer (abbreviated as VPTR), which points to the VTABLE for that object. When you make a virtual function call through a base-class pointer (that is, when you make a polymorphic call), the compiler quietly inserts code to fetch the VPTR and look up the function address in the VTABLE, thus calling the correct function and causing late binding to take place.
All of this – setting up the VTABLE for each class, initializing the VPTR, inserting the code for the virtual function call – happens automatically, so you don’t have to worry about it. With virtual functions, the proper function gets called for an object, even if the compiler cannot know the specific type of the object.