[   ^ to index...   |   <-- previous   ]

Destructors

You might ask, "Well, if a constructor acquires a resource when an object is born, don't we need a way to release those resources when the object dies?

The answer is yes, and the answer is destructors. The most common use of a destructor is to release dynamically allocated memory, which we haven't covered yet. However, jumping ahead (since this is the high-background section, eh) imagine that we defined a CourseList class for a C++ translation of the previous homework assignment. We might use

class CourseList { public: CourseList(char * filename); virtual ~CourseList(); // DESTRUCTOR // ... some stuff, then: private: ifstream * input; // and then some stuff };

The CourseList(char *) constructor might do something like the following:

CourseList::CourseList(char * filename) { input = new ifstream(filename); }

This constructor actually allocates two kinds of resources. First, it allocates a new ifstream object in dynamic memory. Second, the ifstream constructor must of course open a filehandle. Both of these are bad news if we do not release them when the CourseList object is destroyed.

A destructor has the name of the class to which it belongs, with a tilde ~ prepended. The destructor for this class would probably be defined as follows:

CourseList::~CourseList() { delete input; }

The delete keyword deallocates (frees) the ifstream object pointed to by input. The ifstream destructor will automatically be called, and it will release the filehandle.

NOTE: DO NOT USE DYNAMIC MEMORY OR DESTRUCTORS ON YOUR NEXT HOMEWORK ASSIGNMENT UNLESS INSTRUCTED EXPLICITLY TO DO SO.


Last modified: Wed Jun 28 20:22:16 PDT 2000