1

I am having a little bit of trouble understanding when you are writing classes in C++ when you would want to write your own destructor function, overriding the default one? I understand what the purpose of the destructor is, I'm just confused when you would not want to use the one provided by the compiler. Thanks in advance.

4 Answers4

2

A custom destructor is used to release resources that you may have dynamically allocated. For example, if you have allocated dynamic memory using new or malloc, if your class has file handle member variables, or network sockets, your custom destructor would ensure that all these resources are deallocated/closed.

Nicolas Riousset
  • 3,447
  • 1
  • 22
  • 25
2

The compiler will add one for you if you don't provide one, but that may not do what you need it to do. In general, a destructor is mandatory if you are manually allocating static storage memory in your class, usually in a constructor and using new. If you don't also delete it when your class destructs, that memory will not get released and you will have a memory leak = very bad.

But a destructor can be useful for other operations you want done as well upon object removal.

I personally do not usually write destructors because I never allocate memory I must manage myself -- thanks to shared pointers and smart pointers in most modern C++ libraries, you can usually count on memory to automatically get released by using them. For example, Qt has QSharedPointer and std and boost have similar classes for automatic memory management.

Bill Abrams
  • 320
  • 2
  • 9
1

Take a look at the rule of three and at the RAII idiom, you'll see some example of why and when we're defining our own destructor.

nouney
  • 4,363
  • 19
  • 31
1

You need to define a custom destructor whenever you use pointers. Take the following class:

class Foo {
    public:
        Foo(int&);
        Foo();
        ~Foo(); //Custom Destructor
        int* getData();
        void setData();
    private:
       int* data;
    };

Here a class Foo stores a pointer to an integer. Since we are storing a pointer, we need to tell C++ to delete the data pointed to by that pointer when the object is destroyed. To do so, you use the delete keyword as follows:

Foo::~Foo() {
    delete data;
}

If you don't specify a custom destructor, the data will never be deleted even when the object is destroyed. While the 4 bytes to store an integer might not seem like much, in a large program that uses many objects it can add up.

As a side note (you may not have gotten to this, but it's worth mentioning), you should pretty much always specify the destructor as virtual. This way if someone extends the class, the program will call the correct destructor, instead of defaulting to the base class (which is the default behavior in some polymorphic situations).

ahjohnston25
  • 1,915
  • 15
  • 36