構造順序:**基類 → 成員子對象 (按宣告順序) → 派生類本身**
析構順序:完全相反 (派生類 → 成員 → 基類)
class Person {
Person() { cout << "Person ctor\n"; }
~Person() { cout << "Person dtor\n"; }
};
class Student : public Person {
Student() { cout << "Student ctor\n"; }
~Student() { cout << "Student dtor\n"; }
};
class Teacher : public Person {
Teacher() { cout << "Teacher ctor\n"; }
~Teacher() { cout << "Teacher dtor\n"; }
};
int main() {
Student s; Teacher t;
}
/* 輸出:
Person ctor
Student ctor
Person ctor
Teacher ctor
Teacher dtor
Person dtor
Student dtor
Person dtor
*/
每個派生類物件包含獨立的基類子物件。
class Data {
Data(int x) : x(x) { cout << "Data ctor\n"; }
~Data() { cout << "Data dtor\n"; }
int x;
};
class Base {
Base(int x) : d1(x) { cout << "Base ctor\n"; }
~Base() { cout << "Base dtor\n"; }
Data d1;
};
class Device : public Base {
Device(int x) : Base(x), d2(x) { cout << "Device ctor\n"; }
~Device() { cout << "Device dtor\n"; }
Data d2;
};
int main() { Device obj(5); }
/* 輸出:
Data ctor (Base::d1)
Base ctor
Data ctor (Device::d2)
Device ctor
Device dtor
Data dtor (Device::d2)
Base dtor
Data dtor (Base::d1)
*/
class Base {
public:
Base(int xx = 0) : x(xx) { cout << "Base ctor\n"; }
~Base() { cout << "Base dtor\n"; }
int x;
};
class Device : public Base {
public:
Device(int xx = 0, int yy = 0) : Base(xx), y(yy), z(xx+yy) {
cout << "Device ctor\n";
}
~Device() { cout << "Device dtor\n"; }
int y;
Base z; // 另一個 Base 成員
};
/* 輸出順序:
Base ctor (Base::Base(xx))
Base ctor (Device::z)
Device ctor
... dtor 反序
*/
virtual (Effective C++ 條款 7)