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:
There may be only one constructor per class. The name is arbitrary, but it can not have parameters.
There may be only one destructor per class. The name is arbitrary, but it can not have 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.
There is no guaranteed order in which the class constructors or destructors are called. For nested classes, the only guaranteed order is that the constructors of nested classes are called after the constructor of the encompassing class is called, and for the destructors the opposite order is used.
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