Nonvirtual base class destructor

The code below shows the ill effects of hiding a non-virtual constructor of a base class, and then using the derived class as a base one.

// this program is buggy!
#include<iostream>

class Base {
public:
  Base() {
    std::cerr << "constructing Base " << this << std::endl;
    i = new int;
  }
  ~Base() { 
    std::cerr << "destroying Base " << this << std::endl;
    delete i;
  }
private:
  int* i;
};

class Derived : public Base {
public: 
  Derived() {
    std::cerr << "constructing Derived " << this << std::endl;
    d = new double;
  }
  ~Derived() { 
    std::cerr << "destroying Derived " << this << std::endl;
    delete d;
  }
private:
  double* d;
};

int main(int argc, char** argv) {
  using namespace std;
  int ret = 1;  
  Base* thePtr = new Derived;
  delete thePtr;
  return ret;
}  
  
The output of this program is
constructing Base 0x804a008
constructing Derived 0x804a008
destroying Base 0x804a008
This is a bug, because the Derived object was never deallocated. At best, this is a memory leak. In some other cases it may become the source of more serious problems. Can you explain what happened and how to fix the program?



Subsections

Leo Liberti 2008-01-12