Destructors


It's only human nature to destroy that which we build, and programming with classes is no different. Just like there is a set of actions that you do in a class every time you initialize it, there is often a set of actions that you do when you are done using it. Just as we constructed our burrito in the previous example, we go on to the next step of burrito eating, the destruction process where we clean up the mess we left while eating our tasty treat.

And similarly, whenever we finish using a class we have to clean up after ourselves by freeing up any memory which we might have allocated earlier while constructing or using the class. This is where destructors come in.

#include <iostream.h>

class Taco {
  public:
    Taco(int hard) { 
      hardness = new int; 
      *hardness = hard; 
    }
    ~Taco() { 
      cout << "Destroying taco with hardness ";
      cout << *hardness << endl;
      delete hardness; 
    }
  private:
    int* hardness;
};

void main(void) {
  Taco hard(10);
  Taco* soft = new Taco(0);

  delete soft; 
} 

In the above example, notice that destructor methods have the same name as the class, with a ~ added to the front. The other key point to remember from the example is when destructors are called: with pointers to classes, like soft in the above example, the destructor is called when you delete the pointer (and if you don't delete the pointer in your code, then the destructor will never get called, and you will have what is known as a memory leak).

With classes declared staticly, such as Taco hard above, the destructor is called at the end of the function where the object is declared. In the above example, hard's destructor would be called at the end of the main function. C++ does this for you automatically so you don't have to worry about it. This is known as garbage collection.


Table of Contents

Constructors | Destructors | Defining Long Functions | Interface vs. Implementation
Exercises