Destructors in C++

 

·  A destructor is a special member function that works just opposite to constructor, unlike constructors that are used for initializing an object, destructors destroy (or delete) the object.

·        A destructor has the same name as the class, preceded by a tilde (~).

 

   Properties of Destructor :

 

·      Destructor function is automatically invoked when the objects are destroyed.

·        It cannot be declared static or const.

·        The destructor does not have arguments.

·        It has no return type not even void.

·     An object of a class with a Destructor cannot become a member of the union.

·        A destructor should be declared in the public section of the class.

·        The programmer cannot access the address of destructor.

·        The destructor for class A is declared: ~A().

 

   Syntax:

~class_name()    
{   
   //Some code   
} 

 

  Structure of C++ destructors

 

/*...syntax of destructor....*/
 class class_name
 {
      public:
         class_name();    //constructor.
        ~class_name();    //destructor.
}

 

   Example 1Declaration/definition the constructor and destructor

#include<iostream>

using namespace std;

class A{

    public:

      A();        // constructor declaration

     ~A();       // destructor declaration

};

 A::A()           // constructor definition

{

    cout<<”This is a Constructor”;

}

~A::A()       // destructor definition

{

    cout<<”This is a Destructor”;

}

};

int main(){

     A a;          

}

 

 

 

 

When does the destructor get called?

       A destructor is automatically called when:

·        The program finished execution.

·        When a scope (the { } parenthesis) containing local variable ends.

·        When you call the delete operator.

 

   Destructor Example 2:

#include <iostream>
using namespace std;
class Des{
public:
  //Constructor
  Des(){
    cout<<"Constructor is called"<<endl;
  }
  //Destructor
  ~ Des(){
    cout<<"Destructor is called"<<endl;
   }
   //Member function
   void display(){
     cout<<"Hello World!"<<endl;
   }
};
int main(){
   //Object created
   Des obj;
   //Member function called
   obj.display();
   return 0;
}

Output:

Constructor is called
Hello World!
Destructor is called

  


                                    Destructor rules

·        Name should begin with tilde sign(~) and must match class name.

·        There cannot be more than one destructor in a class.

·        Unlike constructors that can have parameters, destructors do not allow any parameter.

·        They do not have any return type, just like constructors.

·        When you do not specify any destructor in a class, compiler generates a default destructor and inserts it into your code

Post a Comment

0 Comments

Close Menu