代码改变世界

虚继承

2013-07-29 13:05  Dirichlet  阅读(787)  评论(0编辑  收藏  举报

图例,典型菱形虚继承。

内存布局:

 虚子类Left, Right在最上,虚基类在最下面,本质是两个虚子类对象的开始部分都含有一个虚指针指向虚表,虚表里有相对于Top的偏移量。

当做Right,Left指针到Top指针的转换时,需要用到这个偏移量。

Right* right;

Left* left;

................

Top* top= right;
Top* top= left;

 

 实例代码: 

#include <iostream>
using namespace std;

class Top 
{
public:
    Top():w(1){}

private:
    int w;
};

class Left : public virtual Top
{
public:
    Left():x(2){}

private:
    int x;
};

class Right : public virtual Top
{
public:
    Right():y(3){}

private:
    int y;
};

class Bottom: public Left, public Right
{
public:
    Bottom():z(4){}

private:
    int z;
};


class Left2
{
public:
    Left2():x(2){}

private:
    int x;
};

class Right2
{
public:
    Right2():y(3){}

private:
    int y;
};

class Bottom2: public Left2, public Right2
{
public:
    Bottom2():z(4){}

private:
    int z;
};


int main()
{
    Bottom * pBottom = new Bottom();
    Right * pRight = pBottom;
    Top * pTop = static_cast<Top *>(pRight);

    Bottom2 * pBottom2 = new Bottom2();
    Right2 * pRight2 = pBottom2;

    return 1;
}

 

问题:这里Top * pTop = static_cast<Top *>(pRight); 是否表明 static_cast就是安全的向上类型转换。

 

参考:

多重继承和虚继承的内存布局     http://blog.csdn.net/littlehedgehog/article/details/5442430

RTTI、虚函数和虚基类的实现方式、开销分析及使用指导 http://baiy.cn/doc/cpp/inside_rtti.htm