Question about destructors

What is a destructor used for? i read about destructors but didnt quite get it, what goes into a destructor? i know it doesnt take any parameters.
What is a destructor used for?


Destructing an object, which usually involves freeing resources (like memory, file handles, et al.) owned by the object being destructed.
If you start using dynamic memory then you should place the delete command in your destructor. If you want a message displayed when a class is destroyed, or if you want a variable changed so you can alert your code that the class is dead, then you would place it in your destructor.

There is always a default destructor for any class if you don't define one, and it functions to clear all variables from that class, but it will only be called when the program ends, and it doesn't handle dynamic memory, so it's a good idea to get into practice of defining your own destructors so you can clear objects that you are finished using.

There are probably other uses for destructors besides what I've listed, but that's what I know so far.
Last edited on
one small note - if you use inheritance and want to write your own destructor for your subclass - the base class destructor is automatically called after your destructor - just because you write your own destructor doesn't mean it overrides the parent class destructors

they are called in the order of inheretance..

1
2
3
4
5
6
7
8
class Base
{};

class Child1 : Base
{};

class Child2 : Child1
{};


if a Child2 instance - say..
Child2 child2;
is destroyed (goes out of scope or is deleted somehow) the destructors will be called as in..

child2.~Child2()
child2.~Child1()
child2.~Base()
Resource cleanup. Destructors enable RAII to provide basic exception safety.
Here's an example from the sticky thread on this board:
http://cplusplus.com/forum/beginner/1988/#msg7682

Another example is:
1
2
3
4
5
6
7
class A
{
  int* i;
public:
  A() { i = new int; }
  ~A() { delete i; }   
};


Just as a small correction:
newbieg mentioned that destructors are called when the program ends. This is true for global objects, but for local objects, the destructors are called when the scope finishes. Example, if you declare your object in a function, the destructor is called at the end of the function.
Topic archived. No new replies allowed.