top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is a destructor in context of C++, details with example will be helpful?

0 votes
412 views
What is a destructor in context of C++, details with example will be helpful?
posted Jan 9, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class.

A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc.

Example:

#include <iostream>

struct A
{
    int i;

    A ( int i ) : i ( i ) {}

    ~A()
    {
        std::cout << "~a" << i << std::endl;
    }
};

int main()
{
    A a1(1);
    A* p;

    { // nested scope
        A a2(2);
        p = new A(3);
    } // a2 out of scope

    delete p; // calls the destructor of a3
}

OUTPUT:

~a2
~a3
~a1
answer Jan 9, 2015 by Amit Kumar Pandey
...