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
Freemethod. Do not callDestroy.Freechecks whether the object reference isnil, and callsDestroyonly for non-nilobject references.Although you can declare a class destructor with any name and arguments, you should declare a single destructor named
Destroy. BecauseDestroyis declared as a virtual method ofTObject, you must declare it with theoverridedirective in your class declaration.The reason you need to override the virtual
Destroydirective 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
Destroyif 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 ornilvalue. Note thatFree,FreeMem, andDisposeautomatically check fornilbefore freeing the object or memory.If you are freeing an object reference ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access