__Virtual function and their implementation

 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{
public:
    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;
    b.CallVirtualFnUsingThis();
 return 0;
}

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

 

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值