构造函数调用顺序
- 调用虚基类构造函数(从左到右)
- 调用非虚基类构造函数(从左到右)
- 调用成员变量构造函数(按声明顺序从前往后,而非初始化列表顺序)
- 调用类自身构造函数的语句
析构函数调用顺序
与构造函数相反
- 执行自身析构函数语句
- 析构成员变量(从后往前)
- 调用非虚基类构造函数(从右到左)
- 调用虚基类构造函数(从右到左)
例子
#include <bits/stdc++.h>
using namespace std;
class Base1 {
public:
Base1() {
cout << "Base1 ctor" << endl;
}
~Base1() {
cout << "Base1 dtor" << endl;
}
};
class Base2 {
public:
Base2() {
cout << "Base2 ctor" << endl;
}
~Base2() {
cout << "Base2 dtor" << endl;
}
};
class VBase {
public:
VBase() {
cout << "VBase ctor" << endl;
}
~VBase() {
cout << "VBase dtor" << endl;
}
};
class A
{
public:
A() {
cout << "A ctor" << endl;
}
~A() {
cout << "A dtor" << endl;
}
};
class B
{
public:
B() {
cout << "B ctor" << endl;
}
~B() {
cout << "B dtor" << endl;
}
};
class Derived: public Base1, public Base2, virtual public VBase {
private:
A a;
B b;
public:
Derived(): b(), a() {
cout << "Derived ctor" << endl;
}
~Derived() {
cout << "Derived dtor" << endl;
}
};
int main(void) {
Derived der;
// Base1 *base = new Derived;
// delete base;
return 0;
}
VBase ctor
Base1 ctor
Base2 ctor
A ctor
B ctor
Derived ctor
Derived dtor
B dtor
A dtor
Base2 dtor
Base1 dtor
VBase dtor
完全符合规则
多态的基类析构函数要声明为 virtual
下面如果使用 Base1 *base = new Derived; delete base;
呢
VBase ctor
Base1 ctor
Base2 ctor
A ctor
B ctor
Derived ctor
Base1 dtor
思考哪出了问题?
其实是为了实现多态,则必须声明基类的析构函数为
virtual
,本题可以将 Base1
的析构函数声明为
virtual
结果:
VBase ctor
Base1 ctor
Base2 ctor
A ctor
B ctor
Derived ctor
Derived dtor
B dtor
A dtor
Base2 dtor
Base1 dtor
VBase dtor