__Virtual function and their implementation

原创 2007年10月01日 23:12:00
 C++ virtual function is ,
       1. a member function of a class
       2. Declare with keyword virtual
       3. Usually has different functionality in derived class
       4. A function call is revolved at run-time.
#include <iostream>
using namespace std;
class Base{
    virtual _cdecl fun(int q){
       cout<<"Hello, base:"<<endl<<q<<endl;
    void CallVirtualFnUsingThis()
       int *p = (int*)this;
       cout<<"Address of the object:"<<hex<<*p<<endl;
       p = (int*)*p;
       cout<<"Address of VPTR:"<<hex<<*p<<endl;
       p = (int*)*p;
       cout<<"address of First function in Vitual table:"<<hex<<*p<<endl;
       void (_cdecl *pFun)(Base* const, int);
       pFun = (void(_cdecl*)(Base* const, int))p;
       (*pFun)(this, 0x25);
int main()
    Base b;
 return 0;

当基类中含有虚函数时, 编译器会自动进行以下的动作:


1、为每一个类增加一个VTABLE VTABLE里记录了各各类里面, 所有在类或基类内声明为virtual的成员函数地址(代码所在地址)。

2、对基类和每个派生类都加入一个VPTR,并对所有这些类所定义对象内的VPTR进行初始化操作:使VPTR指向正确的VTABLE的第一个字段; VPTR是位于对象层次上的概念,当他指向了一个VTABLE时, 就知道自己是什么类型了。。



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.

版权声明:本文为博主原创文章,未经博主允许不得转载。 举报