コンストラクタの逆、つまり
- 派生クラスが先、基底クラスは後
- 複数のクラスを継承する場合、継承宣言の最後から
の順番で呼ばれる。
#include <iostream>
class Base1 {
public:
virtual ~Base1() {
std::cout << "~Base1()\n";
}
};
class Base2 {
public:
virtual ~Base2() {
std::cout << "~Base2()\n";
}
};
class Base3 {
public:
virtual ~Base3() {
std::cout << "~Base3()\n";
}
};
class Derived123: Base1, Base2, Base3 {
public:
virtual ~Derived123() {
std::cout << "~Derived123()\n";
}
};
class Derived321: Base3, Base2, Base1 {
public:
virtual ~Derived321() {
std::cout << "~Derived321()\n";
}
};
class Derived312: Base3, Base1, Base2 {
public:
virtual ~Derived312() {
std::cout << "~Derived312()\n";
}
};
int main() {
auto ptr123 = new Derived123();
std::cout << "deleting Derived123* value\n";
delete ptr123;
std::cout << "\n";
auto ptr321 = new Derived321();
std::cout << "deleting Derived321* value\n";
delete ptr321;
std::cout << "\n";
auto ptr312 = new Derived312();
std::cout << "deleting Derived312* value\n";
delete ptr312;
return 0;
}
deleting Derived123* value
~Derived123()
~Base3()
~Base2()
~Base1()
deleting Derived321* value
~Derived321()
~Base1()
~Base2()
~Base3()
deleting Derived312* value
~Derived312()
~Base2()
~Base1()
~Base3()