先上结论:
当调用构造函数时,首先调用父类的构造函数,其次调用类成员变量的构造函数,最后调用当前类自身的构造函数.
当调用析构函数时(析构函数必须添加 virtual 关键字),首先调用当前类对象的析构函数,其次调用类成员变量的析构函数,最后调用父类的析构函数。
测试代码如下:
// 头文件
#ifndef _TEST_NEW_DELETE_ORDER_H_
#define _TEST_NEW_DELETE_ORDER_H_
#include <iostream>
using namespace std;
class People
{
public:
People()
{
cout << "on people construct" << endl;
}
virtual ~People()
{
cout << "on people destruct." << endl;
}
string name;
};
class Book
{
public:
Book()
{
cout << "on book construct." << endl;
}
~Book()
{
cout << "on book destruct." << endl;
}
};
class Student : public People
{
public:
Student()
:m_book(new Book())
{
cout << "on student construct." << endl;
cout << name.c_str();
}
virtual ~Student()
{
cout << "on student destruct." << endl;
if (m_book)
{
delete m_book;
m_book = nullptr;
}
}
private:
Book *m_book;
};
#endif //_TEST_NEW_DELETE_ORDER_H_
int main()
{
People *stu = new Student();
delete stu;
getchar();
}
打印结果如下:
on people construct
on book construct.
on student construct.
on student destruct.
on book destruct.
on people destruct.
原文:https://www.cnblogs.com/cpp-muggle/p/15129971.html