Don't miss an insight. Subscribe to Techopedia for free.



What Does Destructor Mean?

A destructor is a special method called automatically during the destruction of an object. Actions executed in the destructor include the following:

  • Recovering the heap space allocated during the lifetime of an object
  • Closing file or database connections
  • Releasing network resources
  • Releasing resource locks
  • Other housekeeping tasks

Techopedia Explains Destructor

Destructors are called explicitly in C++. However, in C# and Java this is not the case, as the allocation and release of memory allocated to objects are implicitly handled by the garbage collector. While destructors in C# and Java (called finalizers) are nondeterministic, C# destructors are guaranteed to be called by the .NET run time. However, Java finalizers have to be explicitly invoked since their invocation is not guaranteed.

Key properties of destructors can be summarized as follows:

  • Automatic invocation and no explicit call from user code
  • Overloading or inheritance not allowed
  • Access modifiers or parameters not to be specified
  • Order of call to destructor in a derived class is from the most derived to the least derived
  • Called not only during the object destruction, but also when the object instance is no longer eligible for access
  • Used in classes but not structs
  • Used only to release expensive unmanaged resources (like windows, network connection, etc.) that the object holds, rather than for releasing managed references

Related Terms