destructors

please explain the concept of destructors in c++
i particularly don't understand the
word that it de-initializes memory
It doesnt de-initializes memory, but it is used to do that, for example.

1
2
3
4
Foo::Foo()
{
      int* x = new int; // allocating memory in the constructor
}


The constructor is called whenever you create an object/instance. Destructors are called when you call delete, or when it goes out of scope. So once the object I created stops existing, it calls the destructor which in this case, can de-initialize memory

1
2
3
4
Foo::~Foo()
{
   delete x;
}


This is obviously just a super basic concept. If you youtube Destructors c++ you get a ton of videos explaining a bit more.
Last edited on
A destructor only ever does exactly what you tell it to at the end of an objects life. This could be used to de-allocate memory, or it could be used to zero out memory (so as to avoid read after deletion); it could also be used to write to a log file, flush a stream, decrement a global counter, inform a socket that you intend to disconnect or any other thing that your black little heart might desire. I guess the point that I want to get across here is that saying that a destructor de-initializes\de-allocates memory is a grossly myopic view of it's potential. Anytime you want some set of code to run when an object is no longer needed, that code should go into the objects destructor.
Topic archived. No new replies allowed.