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
With classes declared staticly,
such as |