Destructor

From Free Pascal wiki
Revision as of 14:41, 7 September 2020 by Bart (talk | contribs) (Example: don't ask for "any key" if you require the user to press <Enter>)
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

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.