虚函数与虚析构函数

在类中,有两个与众不同的成员函数,那就是构造函数和析构函数。当构造函数与析构函数遭遇继承和多态,它们的运行状况又会出现什么变化呢?

    多态性是在父类或各子类中执行最合适成员函数。一般来说,只会选择父类或子类中的某一个成员函数来执行。这可给析构函数带来了麻烦!如果有的资源是父类的构造函数申请的,有的资源是子类的构造函数申请的,而虚函数只允许程序执行父类或子类中的某一个析构函数,岂不是注定有一部分资源将无法被释放?为了解决这个问题,虚析构函数变得与众不同。

下面我们就来给析构函数的前面加上保留字 virtual,看看运行的结果会怎么样:

点击(此处)折叠或打开

  1. //animal.h
  2. #include <iostream>
  3. using namespace std;

  4. class Animal
  5. {
  6.     public:
  7.         Animal(int w = 0, int a = 0);
  8.         virtual ~Animal();
  9.     protected:
  10.         int weight;
  11.         int age;
  12. };

  13. Animal::Animal(int w, int a)
  14.     :weight(w), age(a)
  15. {
  16.     cout <<"Animal consturctor is running..." <<endl;
  17. }

点击(此处)折叠或打开

  1. //cat.h
  2. #include "animal.h"

  3. class Cat : public Animal
  4. {
  5.     public:
  6.         Cat(int w = 0, int a = 0);
  7.         ~Cat();
  8. };

  9. Cat::Cat(int w, int a):Animal(w, a)
  10. {
  11.     cout <<"Cat constructor is running..." <<endl;
  12. }
  13. Cat::~Cat()
  14. {
  15.        cout <<"Cat destructor is running..." <<endl;
  16. }

点击(此处)折叠或打开

  1. //main.cpp
  2. #include "cat.h"

  3. int main(void)
  4. {
  5.     Animal *pa=new Cat(2,1);
  6.     Cat *pc=new Cat(2,4);

  7.     cout <<">>> Delete pa <<<" <<endl;
  8.     delete pa;

  9.     cout <<">>> Delete pc <<<" <<endl;
  10.     delete pc;

  11.     return 0;
  12. }
运行结果:
Animal consturctor is running...
Cat constructor is running...
Animal consturctor is running...
Cat constructor is running...
>>> Delete pa <<<
Cat destructor is running...
Animal destructor is running...
>>> Delete pc <<<
Cat destructor is running...
Animal destructor is running...

    发现虚析构函数不再是运行父类或子类的某一个析构函数,而是先运行合适的子类析构函数,再运行父类析构函数。即两个类的析构函数都被执行了,如果两块资源分别是由父类构造函数和子类构造函数申请的,那么使用了虚析构函数之后,两块资源都能被及时释放。

我们修改程序,将 Animal 类析构函数前的 virtual 去掉
运行结果:
Animal consturctor is running...
Cat constructor is running...
Animal consturctor is running...
Cat constructor is running...
>>> Delete pa <<<
Animal destructor is running...
>>> Delete pc <<<
Cat destructor is running...
Animal destructor is running...

    发现运行结果中删除 pa 指向的 Cat 对象时,不执行 Cat 类的析构函数。如果这时 Cat 类的构造函数里申请了内存资源,就会造成内存泄漏了。

所以说,虚函数与虚析构函数的作用是不同的。 虚函数是为了实现多态 ,而 虚析构函数是为了同时运行父类和子类的析构函数,使资源得以释放
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值