c++构造析构顺序
class A
{
public:
A(){ cout << "constrcut A" << endl; };
~A(){ cout << "destruct A" << endl; };
};
class C
{
public:
C(){ cout << "construct C" << endl; };
~C(){ cout << "destruct C" << endl; };
};
class B: public A
{
public:
B(){ cout << "construct B" << endl; };;
~B(){ cout << "destruct B" << endl; };
private:
C c;
};
执行后结果为:
constrcut A
construct C
construct B
destruct B
destruct C
destruct A
即:生成派生类对象时,先执行父类的构造函数,再执行类成员变量的构造函数(依照声明顺序),最后执行派生类构造函数中的内容。
即:
- 父类的构造函数
- 类成员变量的构造函数(依照声明顺序),
- 派生类构造函数
析构顺序相反。