为什么我们没有义务实现纯虚析构函数?

why we are not obliged to implement pure virtual destructor?

制作class抽象是通过将其成员函数之一设为纯虚函数。

创建一个 class 抽象要求 class 的子级实现基本的纯虚函数。

我们甚至可以使基本 class 析构函数成为纯析构函数,这足以成为抽象的 class。

问题:

例如:

#include <iostream>
using namespace std;

class Base
{
    public:
        Base(){cout << "Base Ctor" << endl;}
        virtual ~Base() = 0 {cout << "Virtual base dtor" << endl; }
};

class Derived : public Base
{
    public:
        Derived(){cout << "Derived Ctor" << endl;}
         // virtual ~Derived() {cout << "Virtual Derived dtor" << endl; }
};

int main()
{

    Base* theBase = new Derived;
    delete theBase;

    cout << endl;


    cout << endl << endl;
    return 0;
}

why we are not obliged to implement the pure virtual base's destructor in our derived class?

因为析构函数不会被覆盖。

为了帮助记住这一点,请考虑名称:~Base~Derived 不一样。构造函数和析构函数不是通过覆盖工作,而是在链中调用:最底部的析构函数运行,然后调用其父析构函数,父析构函数运行,然后调用其父析构函数等。

这就是为什么如果您想删除派生的 classes 之一的实例,您 必须 提供析构函数的主体,即使它被标记作为纯虚拟:在析构函数链中到达它时需要一个主体来调用。

那么,虚拟析构函数的处理方式是什么?这样做是为了让编译器在遇到某些 class 的破坏时知道调用最底部的析构函数。所以destruction确实使用了virtual table,只是在derived析构函数完成后它是运行父class析构函数,所以它不是标准的覆盖。

does it mean as long as C++ adds to us four member functions by default: constructor, copy constructor, assignment and Destructor we don't need to implement it in our derived class?

不太明白这个问题,但无论如何默认添加的方法都不是纯虚拟的,可以在继承链中的每个 class 中创建。