Skip to content
LumenaryAcademy
Professional 60 min

Classes, properties and interfaces

Object Pascal's class model, from constructors and destructors to properties and events, inheritance with virtual methods, and reference-counted interfaces.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

Objects the Delphi way

Delphi's designers, in 1995, wanted Object Pascal to support a visual designer: drop a button on a form, set its Caption and Font in a property inspector, and write code for its OnClick. That goal shaped Object Pascal's class model. Classes have properties, which look like fields to the user but can run code when read or written, so setting Button.Caption repaints the button. They have events, properties holding a pointer to a method of another object, so the form can handle the button's click. And every class descends from one root, TObject, so a designer can store, inspect and stream any component.

The same model serves just as well for code with no user interface, and it is what this lesson teaches: classes with constructors and destructors, properties and events, inheritance with virtual methods, and interfaces, which describe a capability any class can provide and, in Object Pascal, also manage memory by reference counting. One thing to keep in mind throughout: objects of classes are not managed types. You create them and you free them, and the try … finally pattern you are about to see is how professionals make sure the freeing always happens.

DefinitionsH

The class model

Definition— Class

A class is a reference type. A variable of a class type holds a reference (a pointer) to an object on the heap, or nil. Objects are created by calling a constructor, conventionally Create, and destroyed by calling Free, which calls the destructor Destroy if the reference is not nil.

Definition— Property

A property is a named member whose reads and writes are mapped to fields or methods: property Celsius: Double read FCelsius write SetCelsius;. A property with only read is read-only. Code using the class writes Sensor.Celsius := 21 and cannot tell whether a field or a method is involved.

Definition— Virtual method

A method marked virtual can be redefined by a descendant with override. A call through a reference of the parent type runs the version belonging to the object's actual class (dynamic dispatch). A method marked virtual; abstract; has no body in the parent and must be overridden.

The parts of a class declaration are grouped into visibility sections:

SectionVisible to
strict privatethe class's own methods only
privatethe class and any code in the same unit
strict protected, protectedthe class and its descendants (plus, for protected, the same unit)
publiceveryone
publishedeveryone, plus run-time type information, so designers and streaming can see it

The plain private of Object Pascal is visible to the whole unit, a historical convenience; strict private gives the encapsulation other languages call private. Conventions: class names start with T, fields with F, and a property X is usually backed by a field FX, a getter GetX and a setter SetX.

Worked examplesH

A class with properties and an event

pascal
program Sensor;
{$mode objfpc}{$H+}

uses
  SysUtils;

type
  TSensor = class;                                      { forward declaration }
  TReadingEvent = procedure(Sender: TSensor) of object; { an event type }

  TSensor = class
  strict private
    FName: string;
    FCelsius: Double;
    FReadings: Integer;
    FOnAlarm: TReadingEvent;
    procedure SetCelsius(AValue: Double);
    function GetFahrenheit: Double;
  public
    constructor Create(const AName: string);
    destructor Destroy; override;
    property Name: string read FName;                        { read-only }
    property Celsius: Double read FCelsius write SetCelsius; { setter validates }
    property Fahrenheit: Double read GetFahrenheit;          { computed }
    property Readings: Integer read FReadings;
    property OnAlarm: TReadingEvent read FOnAlarm write FOnAlarm;
  end;

constructor TSensor.Create(const AName: string);
begin
  inherited Create;
  FName := AName;
  WriteLn('created ', FName);
end;

destructor TSensor.Destroy;
begin
  WriteLn('destroyed ', FName, ' after ', FReadings, ' readings');
  inherited Destroy;
end;

procedure TSensor.SetCelsius(AValue: Double);
begin
  if AValue < -273.15 then
    raise EArgumentException.CreateFmt('%s: %.1f is below absolute zero', [FName, AValue]);
  FCelsius := AValue;
  Inc(FReadings);
  if (FCelsius > 40) and Assigned(FOnAlarm) then
    FOnAlarm(Self);                                    { fire the event }
end;

function TSensor.GetFahrenheit: Double;
begin
  Result := FCelsius * 9 / 5 + 32;
end;

type
  { Any object can handle the event with a method of the right signature. }
  TAlarmPanel = class
    procedure HandleAlarm(Sender: TSensor);
  end;

procedure TAlarmPanel.HandleAlarm(Sender: TSensor);
begin
  WriteLn('  ALARM: ', Sender.Name, ' reads ', Sender.Celsius:0:1, ' C');
end;

const
  Samples: array[1..3] of Double = (21.0, 38.5, 41.2);

var
  Kiln: TSensor;
  Panel: TAlarmPanel;
  T: Double;

begin
  Panel := TAlarmPanel.Create;
  Kiln := TSensor.Create('kiln');
  try
    Kiln.OnAlarm := @Panel.HandleAlarm;
    for T in Samples do
    begin
      Kiln.Celsius := T;
      WriteLn(Kiln.Name, ': ', Kiln.Celsius:0:1, ' C = ', Kiln.Fahrenheit:0:1, ' F');
    end;
    try
      Kiln.Celsius := -300;
      WriteLn('not reached');
    except
      on E: EArgumentException do
        WriteLn('rejected: ', E.Message);
    end;
  finally
    Kiln.Free;                                           { always runs }
    Panel.Free;
  end;
end.

It prints:

text
created kiln
kiln: 21.0 C = 69.8 F
kiln: 38.5 C = 101.3 F
  ALARM: kiln reads 41.2 C
kiln: 41.2 C = 106.2 F
rejected: kiln: -300.0 is below absolute zero
destroyed kiln after 3 readings

Points to study:

  • Creating and freeing. TSensor.Create('kiln') allocates and initialises an object. The try … finally block guarantees that Kiln.Free and Panel.Free run however the try part ends, normally or by an exception. This create-try-finally-free pattern appears thousands of times in any Delphi or Lazarus code base; the line after Create should almost always be try.
  • Constructors and destructors. inherited Create runs the parent's constructor first. Destroy is declared override (it is virtual in TObject) and ends with inherited Destroy. Never call Destroy directly; call Free, which checks for nil.
  • Properties. Name and Readings are read-only. Writing Celsius calls SetCelsius, which validates the value, raises EArgumentException for impossible temperatures, counts readings and fires the alarm. Fahrenheit is computed on every read by GetFahrenheit. Users of the class see three simple properties.
  • Events. TReadingEvent is a procedure … of object type, a pointer to a method together with the object it belongs to. The sensor knows nothing about alarm panels; it just calls FOnAlarm(Self) if someone has assigned a handler. This is exactly how every button's OnClick works in Lazarus and Delphi. The forward declaration TSensor = class; lets the event type mention TSensor before the class is fully declared.
ComputationC

Inheritance and interfaces

Inheritance and virtual methods

pascal
program Staff;
{$mode objfpc}{$H+}

uses
  SysUtils;

type
  TEmployee = class
  private
    FName: string;
  public
    constructor Create(const AName: string);
    function MonthlyPay: Currency; virtual; abstract;   { every kind must say }
    function Describe: string; virtual;
    property Name: string read FName;
  end;

  TSalaried = class(TEmployee)
  private
    FAnnualSalary: Currency;
  public
    constructor Create(const AName: string; AAnnual: Currency);
    function MonthlyPay: Currency; override;
  end;

  THourly = class(TEmployee)
  private
    FRate: Currency;
    FHours: Integer;
  public
    constructor Create(const AName: string; ARate: Currency; AHours: Integer);
    function MonthlyPay: Currency; override;
    function Describe: string; override;
  end;

constructor TEmployee.Create(const AName: string);
begin
  inherited Create;
  FName := AName;
end;

function TEmployee.Describe: string;
begin
  Result := Format('%-8s %10.2f', [Name, Double(MonthlyPay)]);   { MonthlyPay dispatches }
end;

constructor TSalaried.Create(const AName: string; AAnnual: Currency);
begin
  inherited Create(AName);
  FAnnualSalary := AAnnual;
end;

function TSalaried.MonthlyPay: Currency;
begin
  Result := FAnnualSalary / 12;
end;

constructor THourly.Create(const AName: string; ARate: Currency; AHours: Integer);
begin
  inherited Create(AName);
  FRate := ARate;
  FHours := AHours;
end;

function THourly.MonthlyPay: Currency;
begin
  Result := FRate * FHours;
end;

function THourly.Describe: string;
begin
  Result := inherited Describe + Format('  (%d h)', [FHours]);   { extend the parent's version }
end;

var
  Team: array of TEmployee;
  E: TEmployee;
  Total: Currency;
  HourlyCount: Integer;

begin
  Team := [TSalaried.Create('Aiyana', 54000),
           THourly.Create('Bilal', 22.50, 120),
           TSalaried.Create('Chen', 61200),
           THourly.Create('Dagny', 31.00, 64)];
  try
    Total := 0;
    HourlyCount := 0;
    for E in Team do
    begin
      WriteLn(E.Describe);
      Total := Total + E.MonthlyPay;
      if E is THourly then
        Inc(HourlyCount);
    end;
    WriteLn(Format('Total    %10.2f', [Double(Total)]));
    WriteLn('Hourly staff: ', HourlyCount);
    WriteLn('Second employee is a ', Team[1].ClassName);
  finally
    for E in Team do
      E.Free;
  end;
end.

It prints:

text
Aiyana      4500.00
Bilal       2700.00  (120 h)
Chen        5100.00
Dagny       1984.00  (64 h)
Total      14284.00
Hourly staff: 2
Second employee is a THourly

TEmployee declares MonthlyPay as virtual; abstract;, so every descendant must provide it, and Describe as virtual with a default. TEmployee.Describe calls MonthlyPay, and because that call dispatches, the parent's code computes each employee's pay correctly without knowing the descendants. THourly overrides Describe and calls inherited Describe to reuse the parent's text, then appends the hours. E is THourly tests an object's class (including descendants); E as THourly would convert the reference, raising EInvalidCast if the object is not a THourly. ClassName gives the class's name at run time. Pay is held in Currency, so the sums are exact; Format needs a Double for %f, hence the conversions.

The array Team holds references, so the finally block frees each object. Forgetting that loop would leak four objects. Lesson 7's TObjectList can own its objects and free them itself.

Interfaces

An interface declares methods without implementation. A class implements it by listing it after its parent, class(TInterfacedObject, IFormatter), and providing the methods. Code written against the interface works with any implementing class, whatever its ancestry.

pascal
program Interfaces;
{$mode objfpc}{$H+}

uses
  SysUtils;

type
  { An interface: methods only. The GUID lets "as" and Supports query it. }
  IFormatter = interface
    ['{4B6B2C1E-7A5D-4C2B-9E3F-1D2A6B8C9E01}']
    function FormatAmount(Cents: Int64): string;
  end;

  { TInterfacedObject provides reference counting: no Free needed. }
  TPlainFormatter = class(TInterfacedObject, IFormatter)
    function FormatAmount(Cents: Int64): string;
    destructor Destroy; override;
  end;

  TCurrencyFormatter = class(TInterfacedObject, IFormatter)
  private
    FSymbol: string;
  public
    constructor Create(const ASymbol: string);
    function FormatAmount(Cents: Int64): string;
    destructor Destroy; override;
  end;

function TPlainFormatter.FormatAmount(Cents: Int64): string;
begin
  Result := Format('%d.%.2d', [Cents div 100, Cents mod 100]);
end;

destructor TPlainFormatter.Destroy;
begin
  WriteLn('  (plain formatter freed)');
  inherited;
end;

constructor TCurrencyFormatter.Create(const ASymbol: string);
begin
  inherited Create;
  FSymbol := ASymbol;
end;

function TCurrencyFormatter.FormatAmount(Cents: Int64): string;
begin
  Result := FSymbol + ' ' + Format('%.2n', [Cents / 100]);   { %n adds thousands separators }
end;

destructor TCurrencyFormatter.Destroy;
begin
  WriteLn('  (', FSymbol, ' formatter freed)');
  inherited;
end;

{ Works with anything that implements IFormatter. }
procedure PrintInvoice(const F: IFormatter);
begin
  WriteLn('Subtotal: ', F.FormatAmount(1234567));
  WriteLn('Delivery: ', F.FormatAmount(450));
end;

var
  F: IFormatter;

begin
  F := TPlainFormatter.Create;
  PrintInvoice(F);
  F := TCurrencyFormatter.Create('KES');     { the plain one's count drops to 0 }
  PrintInvoice(F);
  WriteLn('Supports IFormatter? ', Supports(F, IFormatter));
  F := nil;                                   { and now the KES one }
  WriteLn('done');
end.

It prints:

text
Subtotal: 12345.67
Delivery: 4.50
  (plain formatter freed)
Subtotal: KES 12,345.67
Delivery: KES 4.50
Supports IFormatter? TRUE
  (KES formatter freed)
done

There is no Free anywhere. By default Free Pascal interfaces are COM-style: interface references are reference-counted, and TInterfacedObject frees the object when its count drops to zero. When F was assigned the KES formatter, the plain formatter's last reference disappeared and it was destroyed at once; F := nil did the same for the KES one. This makes interfaces a convenient way to share objects whose lifetime is hard to track. PrintInvoice takes const F: IFormatter, which avoids needless count updates on each call. The GUID in brackets identifies the interface at run time, so Supports(F, IFormatter) and as can query it.

Two cautions that experienced developers learn early. First, do not mix object references and interface references to the same reference-counted object: the object may be freed while an object reference still points to it. Second, Free Pascal also offers CORBA-style interfaces ({$interfaces corba}), which have no reference counting and no required GUID; they suit designs where objects are freed explicitly and interfaces only describe capabilities.

ExplanationH

How professionals design classes

  • Create, try, use, finally, Free. For every object a routine creates and owns, with nothing between Create and try. When several objects are created, either nest the blocks or initialise all the variables to nil first and free them all in one finally.
  • Ownership is explicit. Every object has exactly one owner responsible for freeing it: a local try … finally, a field freed in the owner's destructor, a container created with ownership, or, in GUI code, a component's Owner. When ownership is unclear, consider an interface.
  • Properties for state, methods for actions. Expose state through properties, with setters that validate, and keep fields private. Use strict private in new code.
  • Small hierarchies. Prefer composition and interfaces to deep inheritance. An abstract base class with one level of descendants, like TEmployee, is common and healthy.
  • Free Pascal versus Delphi. In objfpc mode you assign method pointers with @ (Kiln.OnAlarm := @Panel.HandleAlarm); delphi mode omits it. Delphi also has class helpers, attributes and extended RTTI with differences in detail, so shared code is tested with both compilers.
Common misconceptionsH

Common misunderstandings

Misconception

"Objects are freed automatically when they go out of scope." Class instances are not managed types. Without Free, they leak. Only interface references (to reference-counted objects), strings and dynamic arrays are freed automatically.

Misconception

"Assigning one object variable to another copies the object." It copies the reference: both variables then refer to the same object, and freeing it through one leaves the other dangling. To copy an object, write a method such as Assign (the convention in Delphi and Lazarus, inherited from TPersistent).

Misconception

"private means only the class can see it." In Object Pascal, private members are visible to all code in the same unit. Use strict private for class-only access.

Misconception

"Overriding a method only needs the same name." The parent's method must be virtual (or dynamic), and the child's must say override. A method with the same name but no override hides the parent's instead, and calls through a parent-typed reference still run the parent's version. Free Pascal warns: Warning: An inherited method is hidden by "Name:AnsiString;", and in a test, a TB object called through a TA reference answered with TA's result.

Exercises

Exercises

All outputs below were checked by compiling and running the code with Free Pascal 3.2.2.

1. Classes, properties and interfaces

Warm-upHuman

Why is Kiln.Free placed in a finally block rather than simply at the end of the program?

Choose one

2. Classes, properties and interfaces

CoreComputational

In the sensor program, the samples become (45.0, 40.0, 50.5). How many ALARM lines are printed?

3. Classes, properties and interfaces

Warm-upComputational

A fifth employee, THourly.Create('Eero', 18.00, 0), is added to the team. What does the line Hourly staff: show?

4. Classes, properties and interfaces

StretchComputational

In the interface program, the main block is replaced by:

F := TCurrencyFormatter.Create('INR');
WriteLn(F.FormatAmount(9999999));
F := TPlainFormatter.Create;
WriteLn('done');

What is the line printed immediately before done?

5. Classes, properties and interfaces

CoreComputational

With F := TCurrencyFormatter.Create('INR');, what does WriteLn(F.FormatAmount(9999999)); print?

6. Classes, properties and interfaces

CoreHuman

A class TAccount declares a field FBalance in a plain private section. Which code can read FBalance directly?

Choose one

7. Classes, properties and interfaces

StretchComputational

TA declares function Name: string; virtual; returning 'A'. TB = class(TA) declares function Name: string; (without override) returning 'B'. What does X := TB.Create; WriteLn(X.Name); print when X is declared as TA?

Choose one

Further reading and resources