OOPortal OOPortal


Constructor Functions  «Prev  Next»
Lesson 4 What is a destructor?
Objective Explore the use of destructor member functions.

Destructor Member Functions in C++

A destructor is a member function whose name is the class name preceded by the tilde character (~). A destructor's usual purpose is to destroy values of the class type, typically by using delete.
Destructors
  1. are invoked implicitly when an object goes out of scope. This is typically at block exit for automatic objects and program exit for static objects.
  2. cannot be overloaded or take arguments.

C++ Destructors

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.
A destructor is a member function with the same name as its class prefixed by a ~ (tilde). For example:

class X {
public:
  // Constructor for class X
  X();
  // Destructor for class X
  ~X();
};

A destructor takes no arguments and has no return type. Its address cannot be taken. Destructors cannot be declared const, volatile, const volatile or static. A destructor can be declared virtual or pure virtual. If no user-defined destructor exists for a class and one is needed, the compiler implicitly declares a destructor.
This implicitly declared destructor is an inline public member of its class.

Destructor is the complement of the Constructor

The complement of the constructor is the destructor. In many circumstances, an object will need to perform some action or actions when it is destroyed. Local objects are created when their block is entered, and destroyed when the block is left. Global objects are destroyed when the program terminates. When an object is destroyed, its destructor (if it has one) is automatically called. There are many reasons why a destructor may be needed. For example, an object may need to deallocate memory that it had previously allocated or it may need to close a file that it had opened.
In C++, it is the destructor that handles deactivation events. The destructor has the same name as the constructor, but it is preceded by a ~.
For example, here is the stack class and its constructor and destructor.
(Keep in mind that the stack class does not require a destructor; the one shown here is just for illustration.)

// This creates the class stack.
class stack {
 int stck[SIZE];
 int tos; 
 public:
  stack(); // constructor
  ~stack(); // destructor
  void push(int i);
    int pop();
  };
// stack's constructor
stack::stack()
{
 tos = 0;
 cout <<  "Stack Initialized\n";
}
// stack's destructor
stack::~stack()
{
 cout << "Stack Destroyed\n";
}