#include // CSE 374, example of why destructors should // often be marked virtual // 3/15 BM class Anon { public: ~Anon() { std::cout << "~Anon" << std::endl; } }; class Bnon : public Anon { int* z; public: Bnon() : Anon(), z(new int) { } ~Bnon() { // we allocate an int in the constructor, and we need to delete it in the destructor delete z; std::cout << "~Bnon" << std::endl; } }; class A { public: // It is usually a good idea to make the base class destructor virtual... virtual ~A() { std::cout << "~A" << std::endl; } }; class B : public A { int* z; public: B() : A(), z(new int) { } ~B() { delete z; std::cout << "~B" << std::endl; } }; int main() { { Anon a; }// destructor called std::cout << "--" << std::endl; { Bnon b; }// destructor called std::cout << "--" << std::endl; // ...because if you don't then deleting an object polymorphically (through base class pointer) // won't call the derived class' destructor. Here the memory pointed to by anp->z is leaked!! Anon *anp = new Bnon(); delete anp; std::cout << "--" << std::endl; A *ap = new B(); delete ap; std::cout << std::endl; }