• virtual inheritance


    Virtual inheritance is used to solve the problem of diamonds inheritance, 2 instance of base objects, in multiple inheritance. With the knowledge on c++ object model, we can understand virtual inheritance easily. Here is a sample code.

    #include<iostream>

    using namespace std;

    class Point2D_IF{
    public:
    virtual void print() = 0;
    int x;
    int y;
    };

    class Point2D_impl : public Point2D_IF{
    public:
    virtual void print(){cout<<"in Point2D_impl"<<endl;}
    };

    class CombineStage : public virtual Point2D_IF{
    public:
    CombineStage(){d_p = 0; }
    virtual void print(){if(d_p) d_p->print();}
    void addCombineStage(Point2D_IF * p) {d_p = p;}
    private:
    Point2D_IF * d_p;

    };

    class Point3D : public virtual Point2D_IF, public CombineStage{
    public:
    int z;
    };


    int main()
    {
    Point3D* p3d = new Point3D();
    Point2D_impl* p2d = new Point2D_impl();
    p3d->addCombineStage(p2d);
    p3d->print();

    delete p3d;
    delete p2d;
    cout<<"sizeof(Point2D_IF) "<<sizeof(Point2D_IF)<<endl;
    cout<<"sizeof(Point2D_impl) "<<sizeof(Point2D_impl)<<endl;
    cout<<"sizeof(CombineStage) "<<sizeof(CombineStage)<<endl;
    cout<<"sizeof(Point3D) "<<sizeof(Point3D)<<endl;
    return 0;
    }

    --------------------

    [tli]$ g++ virtualInheritance.cc
    [tli]$ ./a.out
    in Point2D_impl
    sizeof(Point2D_IF) 16
    sizeof(Point2D_impl) 16
    sizeof(CombineStage) 32
    sizeof(Point3D) 40

  • 相关阅读:
    Java8新特性
    为什么要使用ORM技术?和 JDBC 有何不一样?
    HTTP Status 500
    重装Oracle时出现SID已存在问题的解决办法
    数据库模式显示的Swing表格
    自然连接和等值连接
    雷林鹏分享:Java 循环结构
    雷林鹏分享:Java 运算符
    雷林鹏分享:Java 修饰符
    雷林鹏分享:Java 变量类型
  • 原文地址:https://www.cnblogs.com/Torstan/p/2735977.html
Copyright © 2020-2023  润新知