c++ - 如果不是手动完成,子类是否会继承父类的析构函数?

标签 c++ class oop inheritance destructor

如果给定一个包含定义的析构函数的父类 A,B 的子类会在创建 B 对象时执行它吗?即使我没有手动创建也没有继承B类中A的析构函数?

自从我在 c++ 视频教程中看到它以来,我希望它会,但不明白为什么?因为Constructor是手动继承的!

最佳答案

编译器总是为你的类实现一个析构函数,如果你还没有声明的话。编译器还会生成调用基类析构函数的代码。

换句话说,基类析构函数不是继承的,而是在派生类析构函数之后调用的。

参见 Destructor :

Destruction sequence

For both user-defined or implicitly-defined destructors, after the body of the destructor is executed, the compiler calls the destructors for all non-static non-variant members of the class, in reverse order of declaration, then it calls the destructors of all direct non-virtual base classes in reverse order of construction (which in turn call the destructors of their members and their base classes, etc), and then, if this object is of most-derived class, it calls the destructors of all virtual bases.

Even when the destructor is called directly (e.g. obj.~Foo();), the return statement in ~Foo() does not return control to the caller immediately: it calls all those member and base destructors first.

关于c++ - 如果不是手动完成,子类是否会继承父类的析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57391852/

相关文章:

c++ - 动态分配类数组的行为

c++ - 显式加载库的干净方法

ruby-on-rails - 从 Rails 3 中的 lib 文件夹加载模块/类的最佳方法?

c++ - 调用构造函数的次数

c++ - 如何设计避免类型转换

javascript - 是否有人设法通过主要使用 JavaScript 进行开发来自学强大的 OOP 技能?

php - 将权限存储到多维数组php中

c++ - 用 C++ 编写文本/二进制文件最优雅的方法是什么?

java - 内联实例类作为枚举中的参数

c++ - 你如何在 Qt 中使用 unicode?