在派生类中重写哪个基类的虚拟析构函数

Which base class's virtual destructor is overriden in a derived class

本文关键字:基类 虚拟 析构函数 派生 重写      更新时间:2023-10-16

当派生类不是立即派生的,而是从已经派生的类派生时,我对覆盖函数感到困惑。

#include <iostream>
struct Base
{ 
    virtual ~Base() { std::cout << "Base destructor calledn"; }
};
struct Derived : Base
{
    Derived() {}
    // Implicitly supplied destructor, I'm guessing. Which is also virtual?
};
struct MostDerived : Derived
{
    MostDerived(){};
    ~MostDerived() { std::cout << "MostDerived destructor calledn"; }
};
int main()
{
    Derived* d = new MostDerived();
    delete d;
    Base* b = new MostDerived();
    delete b;
}

在这两种情况下,都会调用 MostDerived 的析构函数。我想知道是否只需要最基的类有一个声明为 virtual 的析构函数,在这种情况下,所有其他从它继承的类都有虚拟析构函数,这些虚拟析构函数覆盖上游的所有其他析构函数,如果你明白我的意思。

不确定我是否有意义,基本上如果我有一系列 10 个类,每个类都继承自最后一个类,链中的任何析构函数都会覆盖所有比它更基础的析构函数?

struct GreatGrandfather{~virtual GreatGrandfather(){}}; // Only this is necessary
struct Grandfather : GreatGrandfather {};
struct Father : Grandfather{};
struct Son : Father{};
struct Grandson : Son {};
struct GreatGrandson : Grandson{};
孙子的析构函数

将覆盖其上面的所有类,但不会覆盖曾孙的析构函数?

而且,一旦基类的析构函数或其他函数被声明为虚拟,它的后代就不需要再次声明为虚拟了吗?

链中的任何析构函数

都会覆盖所有比它更基础的析构函数?

是的,差不多。如果您不编写析构函数,则析构函数将由实现隐式提供。因此,它也将隐式覆盖基类 d'tor。

孙子的析构函数

将覆盖其上面的所有类,但不会覆盖曾孙的析构函数?

它将覆盖Son的d'tor。它扩展覆盖Father等等。所以是的。它不能覆盖GreatGrandson,因为在它的定义点上,它不能展望未来并知道GreatGrandson存在。

而且,一旦基类的析构函数或其他函数被声明为虚拟,它的后代就不需要再次声明为虚拟了吗?

是的,与任何虚拟功能相同。一旦声明为 virtual,它在任何派生类中始终是虚拟的。

构函数覆盖基类的所有虚拟析构函数,包括间接基。此外,覆盖虚拟函数的函数本身也是虚拟的。因此,是的,Derived的隐式定义析构函数是虚拟的,~Base~Derived都被~MostDerived覆盖。当指向基类的指针用于销毁派生类类型的对象时,需要为虚拟的析构函数是基类的析构函数。 (派生类中的析构函数将是隐式虚拟的。