`
swincle
  • 浏览: 76628 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Virtual Function Mechanism

    博客分类:
  • C++
 
阅读更多

虚函数(Virtual Function)是通过一张虚函数表(Virtual Table)来实现的。简称为V-Table。 在这个表中,主是要一个类的虚函数的地址表,这张表解决了继承、覆盖的问题,保证其容真实反应实际的函数。这样,在有虚函数的类的实例中这个表被分配在了 这个实例的内存中,所以,当我们用父类的指针来操作一个子类的时候,这张虚函数表就显得由为重要了,它就像一个地图一样,指明了实际所应该调用的函数。

这里我们着重看一下这张虚函数表。在C++的标准规格说明书中说到,编译器必需要保证虚函数表的指针存在于对象实例中最前面的位置(这是为了保证正确取到虚函数的偏移量)。 这意味着我们通过对象实例的地址得到这张虚函数表,然后就可以遍历其中函数指针,并调用相应的函数。

假设我们有这样的一个类:

 

class Base {

public:

virtual void f() { cout << "Base::f" << endl; }

virtual void g() { cout << "Base::g" << endl; }

virtual void h() { cout << "Base::h" << endl; }

};

 

 按照上面的说法,我们可以通过Base的实例来得到虚函数表。 下面是实际例程:

 

typedef void(*Fun)(void);

Base b;

Fun pFun = NULL;

cout << "虚函数表地址:" << (int*)(&b) << endl;

cout << "虚函数表 — 第一个函数地址:" << (int*)*(int*)(&b) << endl;

// Invoke the first virtual function

pFun = (Fun)*((int*)*(int*)(&b));

pFun();

 实际运行经果如下:(Windows XP+VS2003, Linux 2.6.22 + GCC 4.1.3)

 

 

虚函数表地址:0012FED4

虚函数表 — 第一个函数地址:0044F148

Base::f

通过这个示例,我们可以看到,我们可以通过强行把&b转成int *,取得虚函数表的地址,然后,再次取址就可以得到第一个虚函数的地址了,也就是Base::f(),这在上面的程序中得到了验证(把int* 强制转成了函数指针)。通过这个示例,我们就可以知道如果要调用Base::g()和Base::h(),其代码如下:

 

(Fun)*((int*)*(int*)(&b)+0); // Base::f()

(Fun)*((int*)*(int*)(&b)+1); // Base::g()

(Fun)*((int*)*(int*)(&b)+2); // Base::h()

 带虚表的类在对象构造函数中,会把一个指针指向该类虚表地址,我在这给它起个名字叫vp,如图:

Base vp

 

 

 

 

 

 

 

 

 

 

注意:在上面这个图中,我在虚函数表的最后多加了一个结点,这是虚函数表的结束结点,就像字符串的结束符“\0”一样,其标志了虚函数表的结束。这个结束标志的值在不同的编译器下是不同的。在WinXP+VS2003下,这个值是NULL。而在Ubuntu 7.10 + Linux 2.6.22 + GCC 4.1.3下,这个值是如果1,表示还有下一个虚函数表,如果值是0,表示是最后一个虚函数表。

 

下面,我将分别说明“无覆盖”和“有覆盖”时的虚函数表的样子。没有覆盖父类的虚函数是毫无意义的。我之所以要讲述没有覆盖的情况,主要目的是为了给一个对比。在比较之下,我们可以更加清楚地知道其内部的具体实现。

 

一般继承(无虚函数覆盖)

让我们来看看继承时的虚函数表是什么样的。假设有如下所示的一个继承关系:

 

non-vf derive

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

请注意,在这个继承关系中,子类没有重载任何父类的函数。那么,在派生类的实例中,其虚函数表如下所示:

对于实例:Derive d; 的虚函数表如下:

derive d vf-table

 

 

 

 

 

 

 

 

 

 

 

我们可以看到下面几点:

1)虚函数按照其声明顺序放于表中。

2)父类的虚函数在子类的虚函数前面。

 

一般继承(有虚函数覆盖)

如果子类中有虚函数重载了父类的虚函数,会是一个什么样子?假设,我们有下面这样的一个继承关系。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

为了让大家看到被继承过后的效果,在这个类的设计中,我只覆盖了父类的一个函数:f()。那么,对于派生类的实例,其虚函数表会是下面的一个样子:

 

 

 

 

 

 

 

 

 

 

 

我们从表中可以看到下面几点,

1)覆盖的f()函数被放到了虚表中原来父类虚函数的位置。

2)没有被覆盖的函数依旧。

这样,我们就可以看到对于下面这样的程序,

 

Base *b = new Derive();

b->f();
 

由b所指的内存中的虚函数表的f()的位置已经被Derive::f()函数地址所取代,于是在实际调用发生时,是Derive::f()被调用了。这就实现了多态。

 

多重继承(无虚函数覆盖)

下面,再让我们来看看多重继承中的情况,假设有下面这样一个类的继承关系。注意:子类并没有覆盖父类的函数。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

对于子类实例中的虚函数表,是下面这个样子:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

我们可以看到:

1) 每个父类都有自己的虚表。

2) 子类的成员函数被放到了第一个父类的表中。(所谓的第一个父类是按照声明顺序来判断的)

这样做就是为了解决不同的父类类型的指针指向同一个子类实例,而能够调用到实际的函数。

 

多重继承(有虚函数覆盖)

下面我们再来看看,如果发生虚函数覆盖的情况。下图中,我们在子类中覆盖了父类的f()函数。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

下面是对于子类实例中的虚函数表的图:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1:虚表(虚函数表)是for类的
2:基类和派生类是各有各的表,也就是说他们的物理地址是分开的,基类和派生类的虚表的唯一关联是:当派生类没有实现基类虚函数的重写时,派生类会直接把自己表的该函数地址值写为基类的该函数地址值.
3:任何一个有虚表的类,在实例化时不允许其虚表内有项为空->纯虚类不能初始化对象
4:带虚表的类在对象构造函数中,会把一个指针指向该类虚表地址,我在这给它起个名字叫vp;
5:仅对于VC和BC两种编译器论,如果该类带有虚表,那么该类的对象的首地址就是虚表地址,也是this指针指向虚表

我们可以看见,三个父类虚函数表中的f()的位置被替换成了子类的函数指针。这样,我们就可以任一静态类型的父类来指向子类,并调用子类的f()了。如:

 

Derive d;

Base1 *b1 = &d;

Base2 *b2 = &d;

Base3 *b3 = &d;

b1->f(); //Derive::f()

b2->f(); //Derive::f()

b3->f(); //Derive::f()

b1->g(); //Base1::g()

b2->g(); //Base2::g()

b3->g(); //Base3::g()
 

 

安全性

一、通过父类型的指针访问子类自己的虚函数

我们知道,子类没有重载父类的虚函数是一件毫无意义的事情。因为多态也是要基于函数重载的。虽然在上面的图中我们可以看到Base1的虚表中有Derive的虚函数,但我们根本不可能使用下面的语句来调用子类的自有虚函数:

 

Base1 *b1 = new Derive();

b1->f1(); //编译出错
 

 

任何妄图使用父类指针想调用子类中的未覆盖父类的成员函数的行为都会被编译器视为非法,所以,这样的程序根本无法编译通过。但在运行时,我们可以通过指针的方式访问虚函数表来达到违反C++语义的行为。

二、访问non-public的虚函数

 

 

另外,如果父类的虚函数是private或是protected的,但这些非public的虚函数同样会存在于虚函数表中,所以,我们同样可以使用访问虚函数表的方式来访问这些non-public的虚函数,这是很容易做到的。

如:

class Base {

private:

virtual void f() { cout << "Base::f" << endl; }

};

class Derive : public Base{

};

typedef void(*Fun)(void);

void main() {

Derive d;

Fun pFun = (Fun)*((int*)*(int*)(&d)+0);

pFun();

}
 
分享到:
评论

相关推荐

    The implementation mechanism for C++ virtual function

    C++这门语言是一门比较复杂的语言,光从这门语言本身去学习是不够的。 要想更好的使用C++这门编程语言,我们需要了解C++后面的一些东西。 功能点很多,泛泛而谈恐怕效果不是太好。 通过编写程序及使用工具,从另一...

    Selected.Topics.in.Cplusplus.15117

    The Virtual Mechanism Structs, Classes and their Inheritance Object Construction Pointers Non-Constructible, Non-Copyable Class Understanding new Understanding Constructors Forward Declarations, ...

    [精典材料]Patran的PCL用户手册.doc

    Documentation for a typical MSC.Patran built-in function. 144 To get all the nodes and their global coordinates 145 To get the topology of every element 146 To get the shape of every element 147 To ...

    OpenStack Networking Guide

    Distributed Virtual Routing with VRRP IPAM configuration IPv6 Load Balancer as a Service (LBaaS) Logging for security groups Macvtap mechanism driver MTU considerations Open vSwitch with DPDK datapath...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    You can declare functions in a way that allows the compiler to expand them inline rather than calling them through the usual function call mechanism. Pros: Inlining a function can generate more ...

    串口通讯控件

    - Deleted virtual function CommBase.OnRing which was never getting called: use CommBase.OnStatusChange instead. - Fixed bug preventing setting of fAbortOnError in DCB. - Corrected the BaseTerm ...

    LCTF软件备份VariSpec™ Liquid Crystal Tunable Filters

    a) included VsIsPresent() function omitted from function list of 1.10 release Previous release 1.10 Release date: August 28th, 2003 Known bugs: a) VsIsPresent function not included ?generates 搖...

    北京中科信软solaris培训

    The trap mechanism Differentiate between hardware and software interrupts New features in recent releases of the Solaris 10 OS Start using tools such as mdb, kmdb, and DTrace to examine kernel data ...

    The Indispensable PC Hardware Book - rar - part1. (1/7)

    Virtual machines and virtual 8086 monitors. Addresses in virtual 8086 mode. Entering and leaving virtual 8086 mode. Tasks in virtual 8086 mode. 7. Quick buffering: caching. Cache principle and ...

    FlexGraphics_V_1.79_D4-XE10.2_Downloadly.ir

    - ADD: Add TFlexPanel.InvalidateControl virtual method which calls from TFlexControl.Invalidate and can be overriden (it is possible now to catch all object invalidation calls). - FIX: The TFlexPanel....

    Bochs - The cross platform IA-32 (x86) emulator

    - Fix BIOS INT13 function 08 when the number of cylinders on the disk = 1 - I/O Devices - USB HP DeskJet 920C printer device emulation (Ben Lunt) - Misc - Updated Bochs TESTFORM to version 0.5 -...

    Fuzzy Control Systems

    9.1 Generalised Virtual Machines 9.2 A Reconfigurable Architectural Shell with General Knowledge Structures References Chapter 3—Reasoning by Analogy in Fuzzy Controllers 1 Introduction ...

    Practical Mod Perl

    Frontend/Backend Proxying with Virtual Hosts Section 12.11. ...

    php.ini-development

    You can redirect all of the output of your scripts to a function. For ; example, if you set output_handler to "mb_output_handler", character ; encoding will be transparently converted to the ...

    新鲜出炉的PCI-E协议3.0

    Contents OBJECTIVE OF THE SPECIFICATION............................................................................... 23 DOCUMENT ORGANIZATION..........................................................

    Senfore_DragDrop_v4.1

    Delphi's THandle type when a HWND is passed to a function. E.g.: if (DragDetectPlus(THandle(MyControl-&gt;Handle), Point(X, Y))) { ... } * Virtual File Stream formats can only be pasted from the ...

Global site tag (gtag.js) - Google Analytics