[next] [prev] [prev-tail] [tail] [up]

#### 6.4.5 Class constructors and destructors

A class constructor or destructor can also be created. They serve to instantiate some class variables or class properties which must be initialized before a class can be used. These constructors are called automatically at program startup: The constructor is called before the initialization section of the unit it is declared in, the destructor is called after the finalisation section of the unit it is declared in.

There are some caveats when using class destructors/constructors:

- The constructor must be called Create and can have no parameters.
- The destructor must be called Destroy and can have no parameters.
- Neither constructor nor destructor can be virtual.
- The class constructor/destructor is called irrespective of the use of the class: even if a class is never used, the constructor and destructor are called anyway.

The following program:

{$mode objfpc}
{$h+}
Type
TA = Class(TObject)
Private
Function GetA : Integer;
Procedure SetA(AValue : integer);
public
Class Constructor create;
Class Destructor destroy;
Property A : Integer Read GetA Write SetA;
end;
{Class} Function TA.GetA : Integer;
begin
Result:=-1;
end;
{Class} Procedure TA.SetA(AValue : integer);
begin
//
end;
Class Constructor TA.Create;
begin
Writeln(’Class constructor TA’);
end;
Class Destructor TA.Destroy;
begin
Writeln(’Class destructor TA’);
end;
Var
A : TA;
begin
end.

Will, when run, output the following:

Class constructor TA
Class destructor TA

[next] [prev] [prev-tail] [front] [up]