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