C++ Program to demonstrate destructor

Q. Write a program to demonstrate the destructor.

Answer:

  • Destructor is used to destroy the memory allocated by the constructor.
  • The tilde (∼) sign is used to specify the destructor.
  • Destructor is automatically called when the compiler exits from the main program. In the above program, new and delete operator is used to manage the memory automatically.
  • Destructor cannot return or accept any value not even have possibility of destructor overloading.
Following program is demonstrating the destructor.

#include<iostream>
using namespace std;
class TestDestructor
{
        int *t;
    public:
        TestDestructor()
        {
                t = new int;
        }
        void accept()
        {
                cout<<"\n Enter Number : ";
                cin>>*t;
        }
        void display()
        {
                cout<<"\n Entered Number is : "<<*t;
        }
        ∼ TestDestructor()  //Automatically called after the end of the execution.
        {
                delete t;
                cout<<"\n\n Destroyed ";
        }
};
int main()
{
        TestDestructor td;
        td.accept();
        td.display();
        return 0;
}


Output:

destructor