Creating, Instantiating, and Destroying Objects
Go Up to Using the object model Index
Many of the objects you use in the Form Designer, such as buttons and edit boxes, are visible at both design time and runtime. Some, such as common dialog boxes, appear only at runtime. Still others, such as timers and data source components, have no visual representation at runtime.
You may want to create your own classes. For example, you could create a TEmployee class that contains Name, Title, and HourlyPayRate properties. You could then add a CalculatePay method that uses the data in HourlyPayRate to compute a paycheck amount. The TEmployee type declaration might look like this:
type TEmployee = class(TObject) private FName: string; FTitle: string; FHourlyPayRate: Double; public property Name: string read FName write FName; property Title: string read FTitle write FTitle; property HourlyPayRate: Double read FHourlyPayRate write FHourlyPayRate; function CalculatePay: Double; end;
In addition to the fields, properties, and methods you've defined, TEmployee inherits all the methods of TObject. You can place a type declaration like this one in either the interface or implementation part of a unit, and then create instances of the new class by calling the Create method that TEmployee inherits from TObject:
var Employee: TEmployee; begin Employee := TEmployee.Create; end;
The Create method is called a constructor. It allocates memory for a new instance object and returns a reference to the object.
Components on a form are created and destroyed automatically. However, if you write your own code to instantiate objects, you are responsible for disposing of them as well. Every object inherits a Destroy method (called a destructor) from TObject. To destroy an object, however, you should call the Free method (also inherited from TObject), because Free checks for a nil reference before calling Destroy. For example,
destroys the Employee object and deallocates its memory.