Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 36 ยท Classes and Properties

Properties and Visibility

Use private, protected, public and published sections, write properties with read and write accessors, validate values, and add indexed and default properties in Object Pascal.

A class should guard its data. Other code should not be able to put a TAccount into an impossible state, such as a negative balance or an empty name. Object Pascal gives you two tools for that: visibility sections control who can see a member, and properties give callers field-like syntax while your code decides what really happens on read and write.

Properties are one of the best parts of the language. They are also how every component in the Delphi IDE exposes its settings, which is why this lesson matters for VCL forms and components too.

Visibility sections

Each member sits under one of these labels:

Section Who can access it
private the class itself and, in the same unit, any other code
strict private only the class itself
protected the class and its descendants (and, in the same unit, anyone)
strict protected the class and its descendants only
public everyone
published everyone, plus the Object Inspector and streaming of component settings

The surprising part: plain private and protected are relaxed inside the same unit. All code in the unit can see them. That is why Delphi added the strict forms. Most new code uses strict private for fields, so that even helper routines in the same unit have to go through the public interface.

PASCAL
type
  TAccount = class
  strict private
    FOwner: string;
    FBalance: Currency;
  public
    constructor Create(const AOwner: string);
    procedure Deposit(Amount: Currency);
    procedure Withdraw(Amount: Currency);
    property Owner: string read FOwner;
    property Balance: Currency read FBalance;
  end;

Here Owner and Balance are read-only properties: they have read but no write, so Acct.Balance := 1000000; is a compile error. Changing the balance requires Deposit or Withdraw, which can validate.

Property syntax

A property has a type, a read part, and optionally a write part. Each part names a field or a method:

PASCAL
type
  TPerson = class
  strict private
    FName: string;
    FAge: Integer;
    procedure SetAge(const Value: Integer);
  public
    property Name: string read FName write FName;
    property Age: Integer read FAge write SetAge;
  end;

procedure TPerson.SetAge(const Value: Integer);
begin
  if (Value < 0) or (Value > 150) then
    raise Exception.CreateFmt('Invalid age: %d', [Value]);
  FAge := Value;
end;
  • read FName means "reading Name returns the field". There is no call overhead.
  • write SetAge means "assigning to Age calls this setter". The setter is a procedure taking one parameter (conventionally Value), and the place to validate, notify and update dependent values.
  • A read accessor can also be a function with no parameters, for computed values:
PASCAL
property FullName: string read GetFullName;

Callers cannot tell the difference. P.Age := 40; looks like a field assignment, but your validation runs. If you later change the setter's rules, no call site changes.

Name your accessors GetX and SetX, keep them private, and keep the property public. IDE shortcut: put the cursor on a property line and press Ctrl+Shift+C (class completion) in Delphi to generate the missing field and methods.

Why not just a public field?

A public field makes it impossible to add validation, logging or side effects later without changing every caller's code or breaking binary compatibility. A property keeps that door open at no cost. In the other direction, a property with read FName write FName costs nothing at run time: the compiler turns it into a direct field access.

Indexed and default properties

An array property takes index parameters and behaves like an array of values:

PASCAL
type
  TTeam = class
  strict private
    FMembers: TList<string>;
    function GetMember(Index: Integer): string;
    function GetCount: Integer;
  public
    constructor Create;
    destructor Destroy; override;
    property Members[Index: Integer]: string read GetMember; default;
    property Count: Integer read GetCount;
  end;

The word default after the property makes it the class's default array property, so Team[0] is short for Team.Members[0]. That is how TStringList lets you write List[3].

Class properties and stored

A class property belongs to the class and not to an instance, and is usually backed by a class var. The published section also accepts directives such as default (a value that is not saved to the form file) and stored False. You will see them again when forms are saved to .dfm files.

Property tricks you will meet

  • Auto-refresh: setters often call Invalidate or Changed so the screen updates after a change.
  • Lazy creation: the read function creates a helper object on first access.
  • Set-once: a setter that rejects changes after construction.
  • Notification: a setter that fires an event like OnChange when the value really changed (it compares old and new first, to avoid useless events).

The stand-in below models a property as a getter and a setter. The setter validates and also fires a change callback, like an OnChange event. In C there is no property syntax, so callers have to use the function names, but the shape is the same.

C Stand-in: a validating setter with a change callback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Writing to the field inside the class when you meant to use the property: FAge := 200; skips validation, while Age := 200; runs the setter. Inside the class, use the property when you want the rules, and the field when you are the one enforcing them.
  • A setter that assigns to its own property name, Age := Value; inside SetAge, which calls itself forever.
  • Making a published property that depends on other unset properties, which breaks when the form is loaded.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between private and strict private?

    Plain private is unit-wide. strict private limits access to the class, which enforces encapsulation inside the unit too.
  2. 2. A property declared property Total: Currency read GetTotal; can be:

    With no write part the property is read-only, and assigning to it is a compile error.
  3. 3. Why use a setter method in a property?

    The setter runs on every assignment, so it is the place for validation and side effects.
  4. 4. What does default on an array property do?

    A default array property is reached by indexing the object directly, like List[3] on a TStringList.

Summary

  • Visibility sections: strict private, private, strict protected, protected, public, published.
  • A property reads and writes through a field or an accessor method, so callers keep field-like syntax.
  • Setters validate and notify; read-only properties have only read.
  • Array properties take indexes, and default allows Obj[i].
  • Keep fields strict private and expose behavior through properties and methods.

Next: Inheritance and Virtual Methods