RAD Studio |  |

Creating, Instantiating, and Destroying Objects
See Also
Collapse All

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:

Copy Code

    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:

Copy Code

    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,

Copy Code

    Employee.Free;

destroys the Employee object and deallocates its memory.

See Also

Object Pascal and the Class Libraries

Components and Ownership

Using Object Variables

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!