typestar

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

  1. constructor Create(const AGuest: string; ANights: Integer) takes the values the object needs.
  2. The body fills the field with Format('%s: %d nights', [AGuest, ANights]).
  3. Stay := TBooking.Create('Rivera', 3) makes the caller the owner, so Stay.Free sits in finally.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Classes, step 21 of 27 in Language basics.

← Previous Next →