Destructor Keyword


type Class declaration
  destructor Destroy; override;


A destructor cleans up an object and frees its memory. A destructor takes a hidden parameter. This parameter is 1 when the destructor is called from an ordinary method, which tells the destructor to call BeforeDestruction, then run the destructor proper, and finally call FreeInstance to free the object’s memory. When a destructor calls an inherited destructor, the hidden parameter is zero.

Tips and Tricks

  • To free an object, call its Free method. Do not call Destroy. Free checks whether the object reference is nil, and calls Destroy only for non-nil object references.

  • Although you can declare a class destructor with any name and arguments, you should declare a single destructor named Destroy. Because Destroy is declared as a virtual method of TObject, you must declare it with the override directive in your class declaration.

  • The reason you need to override the virtual Destroy directive is because the destructor will often be called polymorphically—where the type declaration of the object reference differs from the object’s actual class.

  • Delphi automatically calls Destroy if a constructor raises an exception. Therefore, you should program defensively. Fields might not be initialized when the destructor is called, so always check for a zero or nil value. Note that Free, FreeMem, and Dispose automatically check for nil before freeing the object or memory.

  • If you are freeing an object reference ...

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.