In
object-oriented programming, a
destructor (sometimes shortened to
dtor) is a
method which is automatically invoked when the
object is destroyed. It can happen when its lifetime is bound to scope and the execution leaves the scope, when it is embedded into another object whose lifetime ends, or when it was allocated dynamically and is released explicitly. Its main purpose is to free the
resources (memory allocations, open files or sockets,
database connections, resource locks, etc.) which were acquired by the object along its life cycle and/or deregister from other entities which may keep references to it. The use of destructors is a necessity to the concept of
Resource Acquisition Is Initialization (RAII).