C++ program to illustrate the use of Destructor in program

//for destroying variables created dynamically using new operator

#include <iostream>
using namespace std;
class Example
{
    private:
        int *ptr;
    public:
    Example() //constructor
    {
        ptr=new int[2];
        //allocate a new integer array, place its address in ptr
    }
    void getdata()
    {
        cout<<"Enter two data:";
        cin>>*(ptr)>>*(ptr+1);
    }
    int getsum()
    {
        return ( *ptr + *(ptr+1) );
    }
    ~Example()
//destructor
    {
        delete ptr;
        cout<<endl<<"Array deleted!!!";
    }
};
int main()
{
    Example e;
    e.getdata();
    cout<<"The sum is "<<e.getsum();
    return 0;
}

No comments:

Post a Comment