Constructor Function in Delphi - ablealias/Delphi GitHub Wiki
A Constructor is a special method that creates and initializes instance objects
. A class can have more than
one constructor. When creating an object you should call a Constructor method of the class. The name of
the Constructor is normally Create, but not restricted to this. An object may be constructed with or without
arguments. Constructor methods you can Override or Overload. See the TObject class Constructor and
Destructor implementation part below, no codes in between the begin and end clause.
constructor TObject.Create;
begin
end;
destructor TObject.Destroy;
begin
end;
To call the parent class Constructor you should specify the Inherited key word as the first statement in your
Constructor implementation part. You can call Constructor using an Object reference or a Class reference.
Delphi passes an additional, hidden parameter to indicate how it was called. If you call a constructor using
a class reference, Delphi calls the class’s NewInstance
method to allocate a new instance of the class. After
calling NewInstance, the Constructor continues and initializes the object. The constructor automatically sets
up a try-except block, and if any exception occurs in the Constructor, Delphi calls the Destructor. See the
Constructor calling using class reference,
var
Account: TSavingsAccount;
begin
Account.Create; // wrong {Object reference}
Account := TSavingsAccount.Create; // right {Class reference}
When you call a Constructor with an object reference, Delphi does not set up the try-except block and does not call NewInstance
. Instead, it calls the constructor the same way it calls any ordinary method.