虚祈构函数

来源:互联网 发布:java分布式面试题 编辑:程序博客网 时间:2024/06/06 02:50

class base
{
public:
        base(){}
        ~base(){ cout<<"hello , I am the base!"<<endl;}
       virtual void fun()
       {
            cout<<"base::fun()"<<endl;
       }
};

class derived : public base
{
public:
       derived(){}
       ~derived(){ cout<<"hello , I am the derived!"<<endl; }
      void fun()
      {
          cout<<"derived::fun()"<<endl;
      }
};


base *p = new derived;
p->fun();
delete p;

上面的程序运行结果是:

derived::fun()

hello , I am the base!

               我们可以看到父类指针要删除子类对象时,子类的祈构函数没有被调用,这造成了子类祈构函数所要完成的功能不能实现(如释放内存资源)。解决上述问题的方法是将父类的祈构函数定义成虚祈构函数,即在前加上关键字virtual。

class base
{
public:
     base(){}
     virtual  ~base(){ cout<<"hello , I am the base!"<<endl;}
     virtual void fun()
     {
           cout<<"base::fun()"<<endl;
     }
};

class derived : public base
{
public:
       derived(){}
      ~derived(){ cout<<"hello , I am the derived!"<<endl; }
      void fun()
      {
            cout<<"derived::fun()"<<endl;
      }
};


base *p = new derived;
p->fun();
delete p;

运行结果为:

derived::fun()

hello , I am the derived!

hello , I am the base!

            所以我们往往将父类的祈构函数定义为虚祈构函数,非父类中我们就不要定义虚祈构函数了,因为存在虚函数,编译器就会给该类建一个虚函数表,这样就不必要的增大了类所占的空间,还有可能降低其可移植性。

原创粉丝点击