Destructor in C++

Destructor:
  • The destructor of the name implies is used to destroy that have been created by the constructor.
  • Whose name is the same as the class name but it is preceded by a title (~).
Rules of destructor:
  • The destructor should start with a tilde(~) and the same name of the class.
  • Destructors do not have parameters and return types.
Uses of destructor:
  • Releasing memory of the objects.
  • Releasing memory of the pointer variables.
  • Closing files and resources.
Syntax:
  1. Class class_name
    {
    class_name()//Constructor
    {
              //statements
    }
    ~class_name()//Destructor
    {
              //statements
    }
    };
Example:
  1. #include<iostream.h>
    #include<conio.h>
    class example
     {
    int a,b;
    public:
    example(int a1, int b1)
    {
    cout<<"\n Allocates memory for Constructor variables.";
    a = a1;
    b = b1;
    }
    void display()
    {
    cout<<"\n Data members for values are:";
    cout<<"\n a = "<< a;
    cout<<"\n b = "<< b;
    }
    ~example()
    {
    cout<<"\n De-allocates the memory for Constructor variables using destructor";
    }
    };
    int main()
    {
    example obj1(7,8);
    obj1.display();
    getch();
    return 0;
    }
Output:
Share:

No comments:

Post a Comment

Popular Posts

Search This Blog

Powered by Blogger.

Blog Archive

Service Support

Need our help to Learn or Post New Concepts Contact me

Blog Archive

Recent Posts

Service Support

Need our help to Learn or Post New Concepts Contact me