Constructors and Free in Delphi
A booking built by a constructor that takes arguments, then freed in a finally block.
program ConstructorFree;
uses SysUtils;
type
TBooking = class
Summary: string;
constructor Create(const AGuest: string; ANights: Integer);
end;
constructor TBooking.Create(const AGuest: string; ANights: Integer);
begin
Summary := Format('%s: %d nights', [AGuest, ANights]);
end;
var Stay: TBooking;
begin
Stay := TBooking.Create('Rivera', 3); // whoever calls Create owns it
try
WriteLn(Stay.Summary);
finally
Stay.Free; // and the owner frees it, on every way out of the block
end;
end.
How it works
constructor Create(const AGuest: string; ANights: Integer)takes the values the object needs.- The body fills the field with
Format('%s: %d nights', [AGuest, ANights]). Stay := TBooking.Create('Rivera', 3)makes the caller the owner, soStay.Freesits infinally.
Keywords and builtins used here
CreateFormatIntegerTBookingWriteLnbeginclassconstconstructorendfinallyprogramstringtrytypeusesvar
The run, in numbers
- Lines
- 20
- Characters to type
- 489
- Tokens
- 101
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 87 seconds.
Step 3 of 3 in Classes, step 21 of 27 in Language basics.