Quick start manual
Classes and objects
7-15
Methods
Destructors
A destructor is a special method that destroys the object where it is called and
deallocates its memory. The declaration of a destructor looks like a procedure
declaration, but it begins with the word destructor. Example:
destructor SpecialDestructor(SaveData: Boolean);
destructor Destroy; override;
Destructors must use the default register calling convention. Although a class can
have more than one destructor, it is recommended that each class override the
inherited Destroy method and declare no other destructors.
To call a destructor, you must reference an instance object. For example,
MyObject.Destroy;
When a destructor is called, actions specified in the destructor implementation are
performed first. Typically, these consist of destroying any embedded objects and
freeing resources that were allocated by the object. Then the storage that was
allocated for the object is disposed of.
Here is an example of a destructor implementation.
destructor TShape.Destroy;
begin
FBrush.Free;
FPen.Free;
inherited Destroy;
end;
The last action in a destructor’s implementation is typically to call the inherited
destructor to destroy the object’s inherited fields.
When an exception is raised during creation of an object, Destroy is automatically
called to dispose of the unfinished object. This means that Destroy must be prepared
to dispose of partially constructed objects. Because a constructor sets the fields of a
new object to zero or empty values before performing other actions, class-type and
pointer-type fields in a partially constructed object are always nil. A destructor
should therefore check for nil values before operating on class-type or pointer-type
fields. Calling the Free method (defined in TObject), rather than Destroy, offers a
convenient way of checking for nil values before destroying an object.
Message methods
Message methods implement responses to dynamically dispatched messages. The
message method syntax is supported on all platforms. WinCLX uses message
methods to respond to Windows messages. Cross-platform portions of CLX do not
use message methods to respond to system events.
A message method is created by including the message directive in a method
declaration, followed by an integer constant between 1 and 49151 which specifies the
message ID. For message methods in WinCLX controls, the integer constant can be
one of the Windows message IDs defined, along with corresponding record types, in