virtual なデストラクタ

基底クラスへのポインタを delete する場合、基底クラスのデストラクタが virtual でないと派生クラスのデストラクタが呼ばれない。

#include <iostream>

struct Base_Non_Virtual {
  ~Base_Non_Virtual() {
    std::cout << "~Base_Non_Virtual()\n";
  }
};

struct Derived_Non_Virtual : Base_Non_Virtual {
  ~Derived_Non_Virtual() {
    std::cout << "~Derived_Non_Virtual()\n";
  }
};

struct Base_Virtual {
  virtual ~Base_Virtual() {
    std::cout << "~Base_Virtual()\n";
  }
};

struct Derived_Virtual : Base_Virtual {
  ~Derived_Virtual() {
    std::cout << "~Derived_Virtual()\n";
  }
};

int main() {
  Base_Non_Virtual *ptr1 = new Derived_Non_Virtual();
  std::cout << "deleting Base_Non_Virtual* value that points to Derived_Non_Virtual value\n";
  delete ptr1;
  std::cout << "\n";
  Base_Virtual *ptr2 = new Derived_Virtual();
  std::cout << "deleting Base_Virtual* value that points to Derived_Virtual value\n";
  delete ptr2;

  return 0;
}
deleting Base_Non_Virtual* value that points to Derived_Non_Virtual value
~Base_Non_Virtual()

deleting Base_Virtual* value that points to Derived_Virtual value
~Derived_Virtual()
~Base_Virtual()

参考

c++ - When to use virtual destructors? - Stack Overflow