4

I'm currently trying to learn about classes and constructors/destructors. I understand what the two do, but I'm having a harder time with the destructors because I can't think of a practical application for its use.

Can anyone provide an example with an explanation?

6 Answers 6

10

Destructors are special member functions used to release any resources allocated by the object.

The most common example is when the constructor of the class uses new, and the destructor uses delete to deallocate the memory.

class Myclass
{
    int *m_ptr;
    public:
        Myclass():m_ptr(new int)
        {
        }
        ~Myclass()
        {
             delete m_ptr;
        }
        //ToDo: Follow Rule of Three
        //Provide definitions for copy constructor & copy assignment operator as well

};
8

Destructors are probably the most important aspect of c++, it manages resources for you and allows you add code to handle any special cleanup such as handle deallocation, disconnections from sockets, DB's etc.. Bjarne Stroustup also states that this is one of the nice things about destructors:

There have also been positive surprises. The most spectacular has been the pervasive use of destructors in techniques relating to resource management and error handling (using exceptions). I knew destructors were a good idea—after all, you have to reverse the effect of a constructor—but I didn't realize quite how central they would be to good use of C++.

Original article: http://msdn.microsoft.com/en-us/magazine/cc500572.aspx

It is also essential to the idiom RAII (Resource Acquisition Is Initialisation) and explained by Bjarne in this article: http://www.artima.com/intv/modern3.html

You can read this C++ faq on destructors which should help you even more.

I think Als code sample is a fine example, you can also look at the code sample in the wikipedia article which is also another example. The fact that the destructor is called when the object goes out of scope or when delete is called is very useful. Something I use is a timer object class to time how long certain function calls take:

class myTimer
{
  mytimer():startTime( TimeNow() )
  {}
  ~myTimer()
  { 
    printf("time taken :%I64d", TimeNow() - startTime);
  }
private:
  __int64 startTime;
};

so in my code I would do something like this

myClass::myFunction()
{
  myTimer timer; // initiliases time to Now.

  someOtherFunc();
} // mytimer object is now out of scope and the destructor is called and prints the time it took
2
  • oh wow that is a pretty neat example. So basically the destructor can also do things other than deallocation of memory?
    – Painguy
    Apr 25, 2012 at 18:22
  • @NimaGanjehloo yes it is not only useful for managing resources but the fact that you know the destructor will be called when the object is deleted or goes out of scope means you can do some pretty useful things in the destructor like signal other threads, spawn threads etc...
    – EdChum
    Apr 25, 2012 at 19:17
2

Imagine you have a class for file operations, e.g. ifstream and you like that this file is closed automaticly the instance of the class go away. Put a close on the file handle in the desctructor.

1

these have the most power when you have composition of dynamically allocated objects

say that I am making linkedList structure that holds pointers to linkedListNodes the list will hold the pointers to the first, and depending on singly, or doubly the last element.

in the destructor I would place the removal of all elements in the list, and therefore the list itself.

If I do not code the destructor then when the list goes out of scope, or has delete called on it the memory that was allocated for those elements is lost, and cannot be reclaimed by the system (most notably called a memory leak)

1

Constructors and Destructors are very important pieces of the RAII (Resource Allocation Is Initialization) idiom. Linking the acquisition of resources (files, memory, sockets, other class objects) to the lifetime of an object is a very powerful tool. When an object goes out of scope, either through normal execution or due to an exception, having the object destructor called allows the class to clean up its resources properly, without having to burden the code using an object with lots of extra finalization steps.

1

Extending @Als's answer here, for example you have a class,

class A {
    B* ptrB; // B is another class / struct / internal type
    A() { ptrB = new B(); }
}

int main() {
    A* ptrA = new A();
    // Do something with A
    delete ptrA; // This does not free ptrA->ptrB
}

To take care of this problem, declare a destructor in A as follows,

~A() { delete ptrB; } // This is called every time delete is called on
                      // an object of A
1
  • Apart from that this code won't compile, your class A is a bomb waiting to explode; double deletions and memory leaks will occur sooner or later. Mar 27, 2013 at 8:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.