Destructor: what changed
Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.
Title: Destructor
| Old | New | Line | |
|---|---|---|---|
| 1 | + | The [[Reserved word|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|class]] (object) is released and therefore no memory leak occurs. | |
| 2 | + | ||
| 3 | + | Release of the object takes place by calling a class `free` [[Method|method]]. Calling `free` causes a `Destroy` invitation. It also checks that the [[Self|self]] [[Variable|variable]] is not [[Nil|nil]]. | |
| 4 | + | ||
| 5 | + | for example: | |
| 6 | + | ||
| 7 | + | ``` pascal | |
| 8 | + | program Project1; | |
| 9 | + | {$ mode objfpc} {$ H +} | |
| 10 | + | ||
| 11 | + | type | |
| 12 | + | ||
| 13 | + | // class definition | |
| 14 | + | {TClass} | |
| 15 | + | ||
| 16 | + | TClass = Class | |
| 17 | + | constructor Create; | |
| 18 | + | destructor Destroy; override; // allows the use of a parent class destroyer | |
| 19 | + | end; | |
| 20 | + | ||
| 21 | + | // class builder | |
| 22 | + | constructor TClass.Create; | |
| 23 | + | begin | |
| 24 | + | Writeln ('Build object'); | |
| 25 | + | end; | |
| 26 | + | ||
| 27 | + | // class eraser | |
| 28 | + | destructor TClass.Destroy; | |
| 29 | + | begin | |
| 30 | + | Writeln ('Demolished Object'); | |
| 31 | + | inherited; // Also called parent class destroyer | |
| 32 | + | end; | |
| 33 | + | ||
| 34 | + | var | |
| 35 | + | ||
| 36 | + | // Defines the class variable | |
| 37 | + | myclass: TClass; | |
| 38 | + | ||
| 39 | + | begin | |
| 40 | + | myclass: = TClass.Create; // Initialize the object by calling the class builder | |
| 41 | + | Writeln ('Something Code ...'); | |
| 42 | + | myclass.Free; // Free invites your own class Destroy discharger | |
| 43 | + | Writeln ('Press <Enter>'); | |
| 44 | + | readln; | |
| 45 | + | end. | |
| 46 | + | ``` | |
| 47 | + | ||
| 48 | + | --- | |
| 49 | + | *From the Free Pascal wiki, page "Destructor", as it stood on 2022-08-06 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).* |
