8.6 — Destructors

A destructor is another special kind of class member function that is executed when an object of that class is destroyed. They are the counterpart to constructors. When a variable goes out of scope, or a dynamically allocated variable is explicitly deleted using the delete keyword, the class destructor is called (if it exists) to help clean up the class before it is removed from memory. For simple classes, a destructor is not needed because C++ will automatically clean up the memory for you. However, if you have dynamically allocated memory, or if you need to do some kind of maintenance before the class is destroyed (eg. closing a file), the destructor is the perfect place to do so.

Like constructors, destructors have specific naming rules:
1) The destructor must have the same name as the class, preceded by a tilde (~).
2) The destructor can not take arguments.
3) The destructor has no return type.

Note that rule 2 implies that only one destructor may exist per class, as there is no way to overload destructors since they can not be differentiated from each other based on arguments.

Let’s take a look at a simple string class that uses a destructor:

Let’s take a look at how this class is used:

This program produces the result:

My name is: Alex

On the first line, we instantiate a new MyString class and pass in the C-style string “Alex”. This calls the constructor, which dynamically allocates memory to hold the string being passed in. We must use dynamic allocation here because we do not know in advance how long of a string the user is going to pass in.

At the end of main(), cMyName goes out of scope. This causes the ~MyString() destructor to be called, which deletes the buffer that we allocated in the constructor!

Constructor and destructor timing

As mentioned previously, the constructor is called when an object is created, and the destructor is called when an object is destroyed. In the following example, we use cout statements inside the constructor and destructor to show this:

This program produces the following result:

Constructing Simple 1
Constructing Simple 2
Destructing Simple 2
Destructing Simple 1

Note that “Simple 1” is destroyed after “Simple 2” because we deleted pSimple before the end of the function, whereas cSimple was not destroyed until the end of main().

As you can see, when constructors and destructors are used together, your classes can initialize and clean up after themselves without the programmer having to do any special work! This reduces the probability of making an error, and makes classes easy to use.

8.7 -- The hidden this pointer
8.5 -- Constructors

41 comments to 8.6 — Destructors

  • kriain1982

    If we instantiate a class by using new operator, we should call destructor explicitly. It won't be called automatically for the objects which are created on the heap.

  • Addmagnet

    " ... However, if you have dynamically allocated memory, or if you need to do some kind of maintenance before the class is destroyed (eg. closing a file) ... "

    I thought it was the object that was destroyed, not the class?

  • Ingegerd

    there are lots of unknown points in this topic for me. For example:
    -what is that "new" when we use it and how it works?
    especially :
    // Allocate a buffer equal to this length
    m_pchString = new char[m_nLength]; ->how it could be possible , how we can write char to an array name?
    -and usage of that "const" keyword at:
    MyString(const char *pchString="")
    these points are unclear for me.I hope somebody can explain.thnx

  • nguyenvulong

    m_nLength = strlen(pchString) + 1;
    m_pchString[m_nLength-1] = '';

    => This one is unnecessary because you don't need to add 1 to nLength and then decrease it by 1 at the second line. Just keep it original :

    MyString(const char *str = "")
    string1len = strlen(str) ;
    string1 = new char[string1len] ;
    strncpy( string1, str, string1len ) ;
    // and you may wanna add string1[string1len] = ''

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">