通常情况下,当创建派生类对象时,首先执行基类的构造函数,随之再执行派生类的构造函数;当撤销派生类对象时,则先执行派生类的析构函数,随后再执行基类的析构函数。
例:
#include<iostream>
using namespace std;
class Base//基类
{
public:
Base()
{
cout<<"Constructing base class"<<endl;
}
~Base()
{
cout<<"Destructing base class"<<endl;
}
};
class Derived:public Base//派生类 公有继承
{
public:
Derived()
{
cout<<"Constructing derived class"<<endl;
}
~Derived()
{
cout<<"Destructing derived class"<<endl;
}
};
int main()
{
Derived obj;
return 0;
}
程序运行结果:
Constructing base class
Constructing derived class
Destructing derived class
Destructing base class
由以上代码可知程序的执行顺序