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:
After the call to Free, the variable A will not be Nil, the output of this program will be:
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):
After the call to FreeAndNil, the variable A will contain Nil, the output of this program will be:
Remark: if an exception happens during an the execution of a constructor, the destructor will be called automatically.