http://www.cnblogs.com/lixiaohui-ambition/archive/2012/07/13/2589716.html

g++ test.cpp -o test

下面这个测试可以说明virtual继承 与虚析构函数的作用

虚继承是解决多重继承中 继承同一个基类导致的 基类多个拷贝
如果去除virtual  基类a被多次构造

base a construct 1

base a1 construct 2

base b construct 3

base a construct 4

base a2 construct 5

base c construct 6

base c destruct5

base a2 destruct4

base a destruct3

base b destruct2

base a1 destruct1

base a destruct0


虚析构是解决用基类指针指向派生类对象,如果没有虚析构函数,其派生类就无法正确析构

去除1处 virtual   b a2 c 无法正常析构

base a construct 1

base a1 construct 2

base b construct 3

base a2 construct 4

base c construct 5

base a1 destruct4

base a destruct3




#include

using namespace std;

int n;

class a{

public:

   a(){cout<<"base a construct "<<(++n)<

   virtual ~a(){cout<<"base a destruct"<<(--n)<

};


class a1: public virtual a

{

public:

a1(){cout<<"base a1 construct "<<(++n)<


 ~a1(){cout<<"base a1 destruct"<<(--n)<

};


class a2: public  virtual a

{

public:

        a2(){cout<<"base a2 construct "<<(++n)<


         ~a2(){cout<<"base a2 destruct"<<(--n)<

};



class b : public a1{

public:

b(){cout<<"base b construct "<<(++n)<


         ~b(){cout<<"base b destruct"<<(--n)<


};


class c : public b,public a2{

public:

c(){cout<<"base c construct "<<(++n)<


         ~c(){cout<<"base c destruct"<<(--n)<


};



int  main()

{

   n = 0;

   

   a1* t = new c();


  delete t;

  

  return 0;


}