Destructor

From Lazarus wiki
Revision as of 09:00, 31 March 2019 by Djzepi (talk | contribs)
Jump to navigationJump to search

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 any key');
   readln;
end.