Object-Oriented Programming In C++: Destructor

Contents:

1. Destructor.

2. When Constructors and Destructors are Called.

Destructor

Is a member function in the class, which has the following characteristics: 1. It has the same name as the class preceded with a tilde '~'. For example, the destructor for class Time is declared: ~Time() 2. It doesn't return any type. 3. It is called when objects are destroyed to release all allocated resources. 4. There is just one destructor in a class, it can not be overloaded.

When Constructors and Destructors are Called:

They are called dynamically and that depends on the scope of objects.

Global Scope Objects:

The constructor is called dynamically before any other function even the main function, and the destructor is called dynamically at the end of the main function.

Local Scope Objects:

The constructor is called dynamically when the object is defined, and the destructor is called dynamically at the end of the block of statements where the object is defined. Example:
  1. // Definition of class CreateAndDestroy.
  2. class CreateAndDestroy
  3. {
  4.     public:
  5.         CreateAndDestroy( int value)  // constructor
  6.         {
  7.              data = value;
  8.              cout << "Object " << data << " constructor";        
  9.         }
  10.         ~CreateAndDestroy()  // destructor
  11.         {
  12.              cout << "Object " << data << " destructor " << endl; }
  13.         }
  14.     private:
  15.         int data;
  16. };
  17.  
  18. void create( void );  // prototype
  19.  
  20. CreateAndDestroy first( 1 );  // global object
  21.  
  22. int main()
  23. {
  24.     cout << " (global created before main)" << endl;
  25.  
  26.     CreateAndDestroy second( 2 );  // local object
  27.     cout << " (local in main)" << endl;
  28.  
  29.     create();  // call function to create objects
  30.     CreateAndDestroy fourth( 4 );  // local object
  31.     cout << " (local in main)" << endl;
  32.     return 0;
  33. }
  34.  
  35. // Function to create objects
  36. void create( void )
  37. {
  38.     CreateAndDestroy fifth( 5 );
  39.     cout << " (local in create)" << endl;
  40.  
  41.     CreateAndDestroy seventh( 7 );
  42.     cout << " (local in create)" << endl;
  43. }
The Output:
Object 1 constructor (global created before main) Object 2 constructor (local in main) Object 5 constructor (local in create) Object 7 constructor (local in create) Object 7 destructor Object 5 destructor Object 4 constructor (local in main) Object 4 destructor Object 2 destructor Object 1 destructor
Note: You can find the full source code of this example in code.zip file.
Tags

Add new comment