The Linux Page

The C++ delete operator, will it do what you expect?

It has always been weird to me to see that the delete operator was not actually going to call all the destructor on objects. That is, if you create a class B that derives from a class A, deleting an object when cast to A does not (by default) call the destructor defined in class B.

The result is that ALL classes should define their destructor as virtual. This doesn't make sense because you shouldn't have to have a virtual table in all your objects just for the destructor to work right. On the other hand, class A has no way to know that it will be derived by class B so its destructor cannot in any way call class B destructor. So it does make sense (it's a simple technical reason.)

Anyway, if you attempt a delete and you leak resources, you probably need to add a virtual on some destructor... The following is a simple example that shows you how C++ breaks when using the delete operator.

  #include <iostream>

  // simple delete test

  class A
  {
  public:
    A() { std::cout << "Built A\n"; }
    ~A() { std::cout << "Destroyed A\n"; }
    //virtual ~A() { std::cout << "Destroyed A\n"; }
  };

  class B : public A
  {
  public:
    B() { std::cout << "Built B\n"; }
    ~B() { std::cout << "Destroyed B\n"; }
  };

  int main(int argc, char *argv[])
  {
    { A *a; a = new A; delete a; }
    std::cout << "----------------\n";
    { B *b; b = new B; delete b; }
    std::cout << "----------------\n";
    { B *b; b = new B; A *a(b); delete a; }
  }