// 例4.8 含有对象成员的派生类构造函数和析构函数的执行顺序。
#include<iostream>
using namespace std;
class Base{ //声明基类Base
public:
Base(int i){ //基类的构造函数
x = i;
cout<<"Constructing base class \n";
}
~Base(){ //基类的析构函数
cout<<"Destructing base class \n";
}
void show(){
cout<<"x="<<x<<endl;
}
private:
int x;
};
class A{
public:
A(){
cout<<"AAAAAAAAA"<<endl;
}
~A(){
cout<<"destructing A class \n";
}
};
class Derived:public Base{ //声明公有派生类Derived
public:
Derived(int i):Base(i){ //派生类的构造函数,缀上要调用的基类构造函数和对象成员构造函数
cout<<"constucting derived class\n";
}
~Derived(){ //派生类的析构函数
cout<<"destructing derived class \n";
}
private:
A d; //d为基类的对象,作为派生类的内嵌对象成员
};
int main(){
Derived obj(5);
obj.show();
return 0;
}
构造函数调用顺序:
先调用基类构造函数、再调用对象成员所在类的构造函数、最后调用派生类构造函数