虚析构函数和纯虚析构函数的作用

1 虚析构函数

作用: 当使用基类的指针删除一个派生类的对象时,可以调用派生类的析构函数。由于有虚函数表的存在,这里就发生了多态,使得派生类的析构函数能够被调用。反之,如果基类的析构函数不是虚函数,则使用基类的指针删除派生类的对象时,不会调用派生类的析构函数。

示例代码如下:

#include 

using namespace std;

class Base
{
public:
    virtual ~Base()
    {
        cout << "~Base()" << endl;
    }
};

class Derived : public Base
{
public:
    ~Derived()
    {
        cout << "~Derived()" << endl;
    }
};

int main()
{

    Base* base = new Derived();

    delete base;

    return 0;
}


输出结果如下:

~Derived()
~Base()

2 纯虚析构函数

作用: 在虚析构函数的基础上使得基类成为抽象类。所以主要有如下两个作用:

  • 删除对象时,所有子类都能进行动态识别
  • 使得基类成为抽象类

注意:

  • 由于最终会调用到基类的析构函数,所以即使基类的析构函数为纯虚的也要给出析构函数的实现,否则产生链接错误 。
  • 当基类的析构函数为纯虚析构函数时,派生类既是不实现析构函数也是可以实例化的,这是因为编译器会为其提供默认的析构函数。

示例代码如下:

#include 

using namespace std;

class Base
{
public:
    virtual ~Base() = 0;
};

Base::~Base()
{
    cout << "~Base()" << endl;
}

class Derived : public Base
{
public:
    ~Derived()
    {
        cout << "~Derived()" << endl;
    }
};

int main()
{

    Base b; // 错误:cannot declare variable 'b' to be of abstract type 'Base'
    Base* base = new Derived();

    delete base;

    return 0;
}


你可能感兴趣的:(虚析构函数和纯虚析构函数的作用)