上級 › 仮想デストラクタが無いと派生クラスのデストラクタが呼ばれない理由 › パターン5
仮想デストラクタが無いと派生クラスのデストラクタが呼ばれない理由
基底クラスのポインタ経由で派生クラスのオブジェクトをdeleteしたとき、基底クラスのデストラクタが仮想(virtual)でないと、派生クラス側のデストラクタが呼ばれないバグです。
1 #include <iostream> 2 class Account { 3 public: 4 ~Account() { std::cout << "Account destroyed" << std::endl; } 5 }; 6 class Savings : public Account { 7 public: 8 ~Savings() { std::cout << "Savings destroyed" << std::endl; } 9 }; 10 int main() { 11 ________ s = new Savings(); ^ 12 delete s; 13 return 0; 14 }
出力: Account destroyed(Savings destroyedが呼ばれない)期待: Savings destroyed → Account destroyed
空欄を埋めてコンパイル・実行を通す
デストラクタの呼び出しも仮想関数と同じく、virtual宣言が無ければポインタの静的な型で決まります。
次の問題