C++ Programming & Tutorials for Beginners

Destructor

Home  »  C++ Programming  »  Destructors


     A destructor is a special member function of the class. The name of the destructor for a class is the tilde (~) character followed by the class name. The destructor is the complement of the constructor. The general form of defining destructor in the class is given below:

~user_define_name();

   The above syntax shows the tilde (~) sign before the constructor name. The name of the constructor is same as that of the class name. A destructor receive no parameters and returns no value. For example :for the class sample, the destructor defined will be ~ sample().

Contents






Destructor

   A class destructor is called when an object is destroyed -e.g. when program execution leave the scope in which an object of that class was initiated. The destructor itself does not actually destroy the object. it performs termination housekeeping before the system reclamis the object's memory so that memory may be reused to hold new objects. Therefore, a destructor is equally useful as is a constructor.

   Generally a destructor is defined under public section of the class, so that its objects can be destroyed in any function. If in case the user fails to define a destructor for a class, the compiler automatically generates one, the default destructor. A class may have only one destructor - destructor over loading is not allowed. The following program shows the use of both constructor and destructor.

Program to show a Consturctor and Destructor.




Note :- To show a Destructor Press Alt + F5


Characteristics of a Destructor

  1. A destructor is invoked automatically by the compiler upon exit from the program and cleans up the memory that is no lenger needed.
  2. A destructor does not return any value.
  3. A destructor cannot be declared as static or const.
  4. A destructor must be declared in public section of data.
  5. A destructor does not accept arguments and therefore it cannot be overloaded.







Previous
Next Post »