Destructor (computer science)

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).

In a language with an automatic garbage collection mechanism, it would be difficult to deterministically ensure the invocation of a destructor, and hence these languages are generally considered unsuitable for RAII. In such languages, unlinking an object from existing resources must be done by an explicit call of an appropriate function (usually called Dispose()). This method is also recommended for freeing resources rather than using finalizers for that.

Destructor syntax

  • C++ has the naming convention in which destructors have the same name as the class of which they are associated with, but prefixed with a tilde (~).
  • In Object Pascal, destructors have the keyword "destructor" and can have user-defined names (but are mostly called "Destroy").
  • In Perl, the destructor method is named DESTROY.
  • In Moose object system for Perl, the destructor method is named DEMOLISH.
  • In Objective-C, the destructor method is named "dealloc".
  • In Swift, the destructor method is named deinit.
  • In PHP 5, the destructor method is named "__destruct". There were no destructors in previous versions of PHP.[1]

In C++

The destructor has the same name as the class, but with a tilde (~) in front of it. If the object was created as an automatic variable, its destructor is automatically called when it goes out of scope. If the object was created with a new expression, then its destructor is called when the delete operator is applied to a pointer to the object. Usually that operation occurs within another destructor, typically the destructor of a smart pointer object.

In inheritance hierarchies, the declaration of a virtual destructor in the base class ensures that the destructors of derived classes are invoked properly when an object is deleted through a pointer-to-base-class. Objects that may be deleted in this way need to inherit a virtual destructor.

A destructor should never throw an exception.[2]



class foo_t
        friend std::ostream & operator << ( std::ostream & os, foo_t const & foo )
                os <<;
                return os;

        char * data;
        foo_t( foo_t const & other );                // disable copy construction
        foo_t& operator = ( foo_t const & other );   // disable assignment

        foo_t( void ) : data( new char[ 14 ] ) { std::strcpy( data, "Hello, World!" ); } 
        ~foo_t( void ) { delete [] data; }
int main()
        foo_t foo;
        std::cout << foo << '\n';

Objects which cannot be safely copied and/or assigned should be disabled from such semantics by declaring their corresponding functions within a non-public encapsulation level (in the above example, "private"). A detailed description of this technique can be found in Scott Meyers' popular book, Effective C++ (Item 6: "Explicitly disallow the use of compiler-generated functions you do not want."[3]).

In C with GCC extensions

The GNU Compiler Collection's C compiler comes with 2 extensions that allow to implement destructors:

  • the "destructor" function attribute allows defining global prioritized destructor functions: when main() returns, these functions are called in priority order before the process terminates. See also [4]
  • the "cleanup" variable attribute allows attaching a destructor function to a variable: the function is called when the variable goes out of scope.


Destructors in REALbasic can be in one of two forms. Each form uses a regular method declaration with a special name (with no parameters and no return value). The older form uses the same name as the Class itself with a ~ (tilde) prefix. The newer form uses the name "Destructor". The newer form is the preferred one because it makes refactoring the class easier.

Class Foobar
  // Old form
  Sub ~Foobar()
  End Sub

  // New form
  Sub Destructor()
  End Sub
End Class

See also


  1. ^ Constructors and Destructors, from PHP online documentation
  2. ^ GotW #47: Uncaught exceptions Accessed 31 July 2011.
  3. ^ Scott Meyers: Effective C++, Addison-Wesley, ISBN 0-321-33487-6
  4. ^ Erickson, Jon (2008). Hacking the art of exploitation. No Starch Press. ISBN . 
This article was sourced from Creative Commons Attribution-ShareAlike License; additional terms may apply. World Heritage Encyclopedia content is assembled from numerous content providers, Open Access Publishing, and in compliance with The Fair Access to Science and Technology Research Act (FASTR), Wikimedia Foundation, Inc., Public Library of Science, The Encyclopedia of Life, Open Book Publishers (OBP), PubMed, U.S. National Library of Medicine, National Center for Biotechnology Information, U.S. National Library of Medicine, National Institutes of Health (NIH), U.S. Department of Health & Human Services, and, which sources content from all federal, state, local, tribal, and territorial government publication portals (.gov, .mil, .edu). Funding for and content contributors is made possible from the U.S. Congress, E-Government Act of 2002.
Crowd sourced content that is contributed to World Heritage Encyclopedia is peer reviewed and edited by our editorial staff to ensure quality scholarly research articles.
By using this site, you agree to the Terms of Use and Privacy Policy. World Heritage Encyclopedia™ is a registered trademark of the World Public Library Association, a non-profit organization.