子类对象在构造时,先调用父类的构造函数,然后再调用自己的构造函数,析构顺序相反。
看下测试代码:
#include <cstdlib>
#include <iostream>
using namespace std;
class grandparent
{
public:
grandparent()
{
cout<<"grandparent()"<<endl;
}
~grandparent()
{
cout<<"~grandparent()"<<endl;
}
};
class Parent : public grandparent
{
public:
Parent()
{
cout<<"Parent()"<<endl;
}
~Parent()
{
cout<<"~Parent()"<<endl;
}
};
class Child : public Parent
{
public:
Child()
{
cout<<"Child()"<<endl;
}
~Child()
{
cout<<"~Child()"<<endl;
}
};
void run()
{
Child child;
}
int main(int argc, char *argv[])
{
run();
cin.get();
return 0;
}
输出结果如下:
结果很明显了,子类构造时,先调用父亲的构造函数,父亲发现他还有父亲,于是父类就去调用子类的爷爷,
调用结束后继续父类的构造,父类构造结束后才调用子类的构造函数,析构时顺序相反~~
更多内容请查看深度探索C++对象模型