destructor
The Destructor keyword defines a destructor procedure Destroy for a class.
When freeing an object, the Destructor is called. This allows the object to
free any storage or other volatile resources it has acquired.
The Name for the destructor is normally destroy, but is not restricted to
this. However, it is very wise to keep to this naming.
The Override directive must be specified since we are overriding the virtual
TObject destroy method.
Example
Download This Source for Free Pascal
{$MODE DELPHI} // Enable "Class"
{$M+} // Enabled "Published"
type
// String holder record
TString = string[10];
// Define a container class
TWords = class
private
wordCount : Integer;
wordsStart : Pointer;
function Get(Index: Integer): string;
public
property GetWord[Index : Integer] : string read Get;
constructor Create(count : integer);
Destructor Destroy; override;
published
end;
var
words : TWords;
// TWords constructor - build the word array
constructor TWords.Create(count: integer);
var
i : Integer;
wordsList : ^TString;
ws:String;
begin
// Get storage for 'count' strings
GetMem(wordsStart, count*SizeOf(TString));
// Fill out this list
wordsList := wordsStart;
wordCount := count;
for i := 1 to count do begin
str(i,ws);
wordsList^ := 'Word '+Ws;
Inc(wordsList);
end;
end;
// TWords destructor - release storage
destructor TWords.Destroy;
begin
// Release memory, if obtained
if wordsStart <> nil then FreeMem(wordsStart);
// Always call the parent destructor after running your own code
inherited;
end;
// GetWord property read function
function TWords.Get(Index: Integer): string;
var
wordsList : ^TString;
begin
// Read the word at the given index, if in range
if (Index >= 1) and (Index <= wordCount) then begin
wordsList := wordsStart;
Inc(wordsList, Index-1);
Result := wordsList^;
end;
end;
Begin
// Create a TWords object
words := TWords.Create(4);
// Now show the 2nd word in this object
Writeln('2nd word = ',words.GetWord[2]);
end.
Output
2nd word = Word 2
See Also
Class,
Constructor,
Function,
Inherited,
Object,
Procedure,
TObject.