代码改变世界

多继承对象的虚函数表

2013-08-05 22:50  Dirichlet  阅读(2823)  评论(0编辑  收藏  举报

子对象多重继承自多个基类,每个基类都有虚函数,那么子类对象的内存布局是什么样的?有一个虚函数表还是多个?

 

示例程序:

 1 #include "iostream"
 2 #include "string" 
 3 #include <typeinfo>
 4 using namespace std;
 5 
 6 
 7 class Base1
 8 {
 9 public:
10     Base1(): x(1){}
11     virtual void QueryInterface() { }
12     virtual void AddRef(){}
13     virtual void Release(){}
14 
15 private:
16     int x;
17 };
18 
19 class Base2
20 {
21 public:
22     Base2(): y(2){}
23     virtual void GetIdsOfNames() { }
24     virtual void Invoke(){}
25 
26 private:
27     int y;
28 };
29 
30 class Base3
31 {
32 public:
33     Base3(): z(3){}
34     virtual void GetMembers() { }
35     virtual void ToString(){}
36 
37 private:
38     int z;
39 };
40 
41 class Derived : public Base1, public Base2, public Base3
42 {
43 public:
44     Derived(): w(4){}
45 private:
46     int w;
47 };
48 
49 void main()
50 {
51     Derived * pd = new Derived;
52 
53 }

 

Debug Info:

cl main.cpp /d1reportSingleClassLayoutDerived

 

所以子对象有三个虚函数表,分别对应于三个基类。

 

参考:

http://www.cnblogs.com/dsky/archive/2012/02/07/2340984.html