Name
Destructor Keyword
Syntax
type Class declaration
destructor Destroy; override;
end;
Description
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 callDestroy
.Free
checks whether the object reference isnil
, and callsDestroy
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
. BecauseDestroy
is declared as a virtual method ofTObject
, you must declare it with theoverride
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 ornil
value. Note thatFree
,FreeMem
, andDispose
automatically check fornil
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.