The Destructor

A destructor is a special member function of a C++ class called when an object's lifetime ends. Like a copy constructor, only one destructor can exist for a class. Since they execute when an object's lifetime ends, destructors typically define the actions necessary to release any resources that an object may be using. For example, consider an object that opens a connection to a database. When this object's lifetime ends, the destructor could close the database connection.

We examine more important uses of destructors in page 1.4.3 Dynamic Memory Management when we discuss dynamic memory management. Until then, we can look at a listing to see at least what the definition of a destructor looks like in C++.

1: 2: 3: 4: 5: ~BankAccount() { if (balance() < 0) { cout << "Warning: negative balance!" << endl; }}
Listing 5 The destructor

The difference between the definition of a destructor and a constructor is very subtle. Notice in line 1 of Listing 5 that a tilde (~) exists in front of the name of the class. This signifies that this member function is the destructor for the class.