Destructor-in-C++ .

In this session i have discussed destructor in C++ .


Destructor , It is clear from name , It is used to destroy the object that is created by constructor . Like constructor the destructor name same as class name but preceded by the tild .

Destructor do not take any argument . It does not return any value . You do not need to call the constructor . It will be implicitly call by the compiler . It will free the memory space for future use . So it is good practice to use the destructor in your program .

Destructor syntax

    ~A(); //Destructor declared
    

Destructor :

Example :Write a program that demonstrate the use of destructor in C++ .

    #include<iostream>
    using namespace std;  
    class A
    {
        public :
            A()
            {
                cout<<"\nObject created";
            }
            void show()
            {
                cout<<"\nThis is show()";
            }
            ~A()
            {
                cout<<"\nObject destroyed";
            }     
    };
    int main()
    {
        A obj;
        obj.show();
        return 0;
    }
    
   OUTPUT : Object is created 
            This is show()
            Object is destroyed
   

Welcome to AndroidATPoint.

back image                     next image