6.4 Class destruction

Class instances must be destroyed using the destructor. In difference with the constructor, there is no choice in destructors: the destructor must have the name Destroy, it must override the Destroy destructor declared in TObject, cannot have arguments, and the inherited destructor must always be called.

Destroy will call FreeInstance, which, in its default implementation, calls FreeMem to release the memory occupied by the instance.

To avoid calling a destructor on a Nil instance, it is best to call the Free method of TObject. This method will check if Self is not Nil, and if so, then it calls Destroy. If Self equals Nil, it will just exit.

Destroying an instance does not remove or Nil a reference to an instance:

Var  
  A : TComponent;  
 
begin  
  A:=TComponent.Create;  
  A.Name:=’MyComponent’;  
  A.Free;  
  Writeln(’A is still assigned: ’,Assigned(A));  
end.

After the call to Free, the variable A will not be Nil, the output of this program will be:

A is still assigned: TRUE

To make sure that the variable A is cleared after the destructor was called, the function FreeAndNil from the SysUtils unit can be used. It will call Free and will then write Nil in the object pointer (A in the above example):

Var  
  A : TComponent;  
 
begin  
  A:=TComponent.Create;  
  A.Name:=’MyComponent’;  
  FreeAndNil(A);  
  Writeln(’A is still assigned: ’,Assigned(A));  
end.

After the call to FreeAndNil, the variable A will contain Nil, the output of this program will be:

A is still assigned: FALSE

Remark: if an exception happens during an the execution of a constructor, the destructor will be called automatically.