Virtual destructors

http://www.gotw.ca/publications/mill18.htm


Virtual destructors are useful when you can delete an instance of a derived class through a pointer to base class
class Base 
{
    // some virtual methods
};

class Derived : public Base
{
    ~Derived()
    {
        // Do some important cleanup
    }
}
What happens if we do the following?

 Base *b = new Derived();
// use b
delete b; // Here's the problem! Since Base's destructor is not virtual,
          // it's ~Base that is called and not ~Derived. Therefore, all the important
          // cleanup is not performed, which can create several resource leaks

Comentarios

Entradas populares