虚祈构函数

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!

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值