C++析构函数调用顺序

C++析构函数调用顺序教程

C++ 中,我们使用子类 继承 父类时,当析构子类时,一定会优先调用子类的 析构函数,接着,才会调用父类的析构函数,这正好跟 构造函数 的调用顺序相反。

案例

C++析构数调用顺序

子类继承父类时,析构子类,会优先调用子类析构函数

#include <iostream> using namespace std; //人类 class Person { public: Person() { cout << "Call Person" << endl; } ~Person() { cout << "Call ~Person" << endl; } }; //学生类 class Student : public Person { public: Student() { cout << "Call Student" << endl; } ~Student() { cout << "Call ~Student" << endl; } }; int main(void) { cout << "嗨客网(www.haicoder.net)\n" << endl; Student stu; return 0; }

程序运行后,控制台输出如下:

10_C析构函数调用顺序.png

从以上案例可以看出,我们在实例化子类 Student 时,首先调用了父类的构造函数,接着调用了子类的构造函数。接着,在析构子类时,优先调用了子类的析构函数,最后才调用父类的析构函数。

C++构造函数调用顺序

子类继承父类时,析构子类,会优先调用子类析构函数

#include <iostream> using namespace std; //人类 class Person { public: Person() { cout << "Call Person" << endl; } ~Person() { cout << "Call ~Person" << endl; } }; //学生类 class Student : public Person { public: Student() { cout << "Call Student" << endl; } ~Student() { cout << "Call ~Student" << endl; } }; class HighSchoolStudent : public Student { public: HighSchoolStudent() { cout << "Call HighSchoolStudent" << endl; } ~HighSchoolStudent() { cout << "Call ~HighSchoolStudent" << endl; } }; int main(void) { cout << "嗨客网(www.haicoder.net)\n" << endl; HighSchoolStudent stu; return 0; }

程序运行后,控制台输出如下:

11_C析构函数调用顺序.png

我们可以看出,当我们的继承有多级关系时,会优先调用最顶层的基类,接着一层一层的往下调用,一直调用到当前实例化的子类的构造函数。当我们析构子类时,会优先析构子类,接着一层层往上析构父类。

C++析构函数调用顺序总结

在 C++ 中,我们使用子类继承父类时,当析构子类时,一定会优先调用子类的析构函数,接着,才会调用父类的析构函数,这正好跟构造函数的调用顺序相反。