Difference between revisions of "Destructor"
From Free Pascal wiki
Jump to navigationJump to searchm (Example: don't ask for "any key" if you require the user to press <Enter>) |
|||
Line 1: | Line 1: | ||
{{Destructor}} | {{Destructor}} | ||
− | The [[Reserved word|reserved word]] <syntaxhighlight lang="pascal" | + | The [[Reserved word|reserved word]] <syntaxhighlight lang="pascal" inline>destructor</syntaxhighlight> belongs to [[object-oriented programming]]. The destroyer is used to release resources like memory. |
The destroyer must always be made so that when the memory is released, the memory used by the entire [[Class|class]] (object) is released and therefore no memory leak occurs. | The destroyer must always be made so that when the memory is released, the memory used by the entire [[Class|class]] (object) is released and therefore no memory leak occurs. | ||
− | Release of the object takes place by calling a class <syntaxhighlight lang="pascal" | + | Release of the object takes place by calling a class <syntaxhighlight lang="pascal" inline>free</syntaxhighlight> [[Method|method]]. Calling <syntaxhighlight lang="pascal" inline>free</syntaxhighlight> causes a <syntaxhighlight lang="pascal" inline>Destroy</syntaxhighlight> invitation. |
− | It also checks that the [[Self|<syntaxhighlight lang="pascal" | + | It also checks that the [[Self|<syntaxhighlight lang="pascal" inline>self</syntaxhighlight>]] [[Variable|variable]] is not [[Nil|<syntaxhighlight lang="pascal" inline>nil</syntaxhighlight>]]. |
Latest revision as of 17:19, 6 August 2022
│
Deutsch (de) │
English (en) │
suomi (fi) │
The reserved word destructor
belongs to object-oriented programming. The destroyer is used to release resources like memory.
The destroyer must always be made so that when the memory is released, the memory used by the entire class (object) is released and therefore no memory leak occurs.
Release of the object takes place by calling a class free
method. Calling free
causes a Destroy
invitation.
It also checks that the self
variable is not nil
.
for example:
program Project1;
{$ mode objfpc} {$ H +}
type
// class definition
{TClass}
TClass = Class
constructor Create;
destructor Destroy; override; // allows the use of a parent class destroyer
end;
// class builder
constructor TClass.Create;
begin
Writeln ('Build object');
end;
// class eraser
destructor TClass.Destroy;
begin
Writeln ('Demolished Object');
inherited; // Also called parent class destroyer
end;
var
// Defines the class variable
myclass: TClass;
begin
myclass: = TClass.Create; // Initialize the object by calling the class builder
Writeln ('Something Code ...');
myclass.Free; // Free invites your own class Destroy discharger
Writeln ('Press <Enter>');
readln;
end.