1

I would like to concentrate on what happens when we say delete ptr. I know that a destructor of our class is called and then the amount of space new allocated is reclaimed.

If our object has other pointers etc, would that be reclaimed as well or is it up to the definition of our constructor to do so?

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Bober02
  • 15,034
  • 31
  • 92
  • 178

3 Answers3

3

The destructor is responsible for clearing up all the resources an object owns. That includes calling delete on pointers that require it. If your destructor does not do this, then you will get a memory leak.

If your objects has members with automatic storage duration, then the destructors of those members are called automatically. This is the foundation of RAII.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
2

If the object that you delete has pointers to other objects or blocks of memory then no, those will not be automatically deleted if your object is deleted. You have to take care of that yourself; the appropriate place to do that is most likely in the destructor of the class of your object.

If you don't deallocate all memory properly then your program has a memory leak.

Jesper
  • 202,709
  • 46
  • 318
  • 350
1

It's up to the definition of your destructor (not constructor).

Graham Borland
  • 60,055
  • 21
  • 138
  • 179