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.
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:
| Section | Visible to |
|---|---|
strict private | the class's own methods only |
private | the class and any code in the same unit |
strict protected, protected | the class and its descendants (plus, for protected, the same unit) |
public | everyone |
published | everyone, 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.
A class with properties and an event
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:
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 readingsPoints to study:
- Creating and freeing.
TSensor.Create('kiln')allocates and initialises an object. Thetry … finallyblock guarantees thatKiln.FreeandPanel.Freerun however thetrypart 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 afterCreateshould almost always betry. - Constructors and destructors.
inherited Createruns the parent's constructor first.Destroyis declaredoverride(it is virtual inTObject) and ends withinherited Destroy. Never callDestroydirectly; callFree, which checks fornil. - Properties.
NameandReadingsare read-only. WritingCelsiuscallsSetCelsius, which validates the value, raisesEArgumentExceptionfor impossible temperatures, counts readings and fires the alarm.Fahrenheitis computed on every read byGetFahrenheit. Users of the class see three simple properties. - Events.
TReadingEventis aprocedure … of objecttype, a pointer to a method together with the object it belongs to. The sensor knows nothing about alarm panels; it just callsFOnAlarm(Self)if someone has assigned a handler. This is exactly how every button'sOnClickworks in Lazarus and Delphi. The forward declarationTSensor = class;lets the event type mentionTSensorbefore the class is fully declared.
Inheritance and interfaces
Inheritance and virtual methods
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:
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 THourlyTEmployee 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.
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:
Subtotal: 12345.67
Delivery: 4.50
(plain formatter freed)
Subtotal: KES 12,345.67
Delivery: KES 4.50
Supports IFormatter? TRUE
(KES formatter freed)
doneThere 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.
How professionals design classes
- Create,
try, use,finally,Free. For every object a routine creates and owns, with nothing betweenCreateandtry. When several objects are created, either nest the blocks or initialise all the variables tonilfirst and free them all in onefinally. - 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'sOwner. 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 privatein 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
objfpcmode you assign method pointers with@(Kiln.OnAlarm := @Panel.HandleAlarm);delphimode omits it. Delphi also has class helpers, attributes and extended RTTI with differences in detail, so shared code is tested with both compilers.
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
All outputs below were checked by compiling and running the code with Free Pascal 3.2.2.
1. Classes, properties and interfaces
Warm-upHumanWhy is Kiln.Free placed in a finally block rather than simply at the end of the program?
2. Classes, properties and interfaces
CoreComputationalIn the sensor program, the samples become (45.0, 40.0, 50.5). How many ALARM lines are printed?
3. Classes, properties and interfaces
Warm-upComputationalA 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
StretchComputationalIn 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
CoreComputationalWith F := TCurrencyFormatter.Create('INR');, what does WriteLn(F.FormatAmount(9999999)); print?
6. Classes, properties and interfaces
CoreHumanA class TAccount declares a field FBalance in a plain private section. Which code can read FBalance directly?
7. Classes, properties and interfaces
StretchComputationalTA 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?
Further reading and resources
- Free Pascal Reference Guide: Classes and InterfacesClass declarations, visibility, properties, virtual methods and interfaces in detail.
- Embarcadero DocWikiThe Delphi language guide's chapters on classes, properties, events and interfaces.
- Free Pascal wikiArticles on Object Pascal classes and the differences between Free Pascal and Delphi.