6.5.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 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