Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 36 ยท Classes and Properties

Classes and Objects

Declare Object Pascal classes, create and free objects safely with try..finally, understand object references versus records, and see the idea in a runnable C stand-in.

Records hold data. Classes hold data and the routines that work on it, and they add inheritance, polymorphism and controlled lifetimes. Object Pascal, the language behind Delphi and Free Pascal, builds everything from the VCL forms to the database layer on classes.

This lesson covers declaring a class, creating objects, and the single rule that causes most beginner bugs: who frees the object.

Declaring a class

A class is declared in the type section, usually in a unit's interface, and its methods are implemented in the implementation section with the class name in front:

PASCAL
type
  TCounter = class
  private
    FValue: Integer;
  public
    constructor Create(AStart: Integer);
    procedure Increment;
    function Value: Integer;
  end;

constructor TCounter.Create(AStart: Integer);
begin
  inherited Create;
  FValue := AStart;
end;

procedure TCounter.Increment;
begin
  Inc(FValue);
end;

function TCounter.Value: Integer;
begin
  Result := FValue;
end;

By convention class names begin with T (type) and fields with F. Fields are the data; the private label hides them from other units (the full story of visibility is in properties and visibility). Self inside a method means the object the method was called on.

Creating and freeing objects

A class variable is a reference (a pointer) to an object that lives on the heap. Declaring the variable creates no object:

PASCAL
var
  C: TCounter;
begin
  C := TCounter.Create(10);   // allocates the object, runs the constructor
  try
    C.Increment;
    WriteLn(C.Value);          // 11
  finally
    C.Free;                    // runs the destructor, releases the memory
  end;
end;

Create is a constructor: you call it on the class name, and it returns a new object. Free is a method of TObject that destroys the object; it checks for nil first, so it is safe to call twice on a variable that you set to nil.

The try ... finally pattern is the heart of safe Delphi code: whatever happens between try and finally (even an exception), the finally part runs and frees the object. Make it a habit: create, then try, then free in finally. More about it in interfaces and exceptions.

Do not put the Create call inside the try block. If Create itself fails, the finally block would call Free on a variable that was never assigned. Put Create just before try.

References, nil and aliasing

Because a class variable is a reference, assignment copies the reference and not the object:

PASCAL
var
  A, B: TCounter;
begin
  A := TCounter.Create(0);
  B := A;          // B and A now point at the SAME object
  B.Increment;
  WriteLn(A.Value); // 1
  A.Free;           // the object is gone
  // B is now a dangling reference: using it is a bug
end;

A reference that points to nothing is nil. Calling a method through a nil reference raises an "Access violation". Two more tools help: Assigned(Obj) tests for non-nil, and FreeAndNil(Obj) frees the object and sets the variable to nil in one step, which prevents most dangling-pointer mistakes for fields.

A class variable is a reference

Variable Holds an address
Object Lives on the heap
Assignment Copies the address
Free Releases the object

Two variables can name one object

1 / 2

Classes versus records

Record Class
Stored inline (stack or inside another type) on the heap, via a reference
Assignment copies all fields copies the reference
Lifetime automatic you free it (or an owner does)
Inheritance no yes
Methods yes (since Delphi 2006) yes

Use a record for small value-like data (a point, a color, a date range). Use a class when identity matters, when several parts of the program must share the same object, or when you need inheritance and virtual methods.

Ownership: who frees what

The rule is simple: whoever creates an object is responsible for freeing it, unless it hands that duty to an owner. Common owners:

  • a TObjectList<T> with OwnsObjects = True frees its items,
  • a form frees the components it owns (see VCL forms and components),
  • a parent object frees child objects in its own destructor.

Every class you write that holds other objects needs a destructor to free them:

PASCAL
type
  TOrder = class
  private
    FLines: TObjectList<TOrderLine>;
  public
    constructor Create;
    destructor Destroy; override;
  end;

constructor TOrder.Create;
begin
  inherited Create;
  FLines := TObjectList<TOrderLine>.Create;
end;

destructor TOrder.Destroy;
begin
  FLines.Free;
  inherited Destroy;
end;

You override Destroy, never call it yourself: callers call Free. Note that Delphi on all platforms uses manual lifetimes for classes; older mobile compilers used automatic reference counting, but it was removed in Delphi 10.4, so the rules above apply everywhere. Free Pascal has always worked this way.

A stand-in in C

C has no classes, but a struct plus functions that take a pointer to it is exactly how a class works inside. The runnable program creates two counters, shows aliasing through a copied pointer, and prints the free pattern. counter_create plays the constructor and counter_free the destructor.

C Stand-in: TCounter as a struct, with aliasing

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.

The line that clears b is the tax for aliasing: when two references point at one object, freeing through one leaves the other pointing at freed memory. Pascal programs avoid this by deciding on one owner.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. After B := A; where both are class variables, what is true?

    Class variables are references. Assignment copies the reference, so both names reach one object.
  2. 2. Where should you place the Create call relative to try?

    Creating before try ensures the finally block only frees an object that really exists.
  3. 3. What does FreeAndNil(Obj) do?

    It destroys the object and clears the reference so you cannot use a dangling pointer by accident.
  4. 4. Which should you override in a class that owns other objects?

    You override Destroy to release owned objects, and callers always use Free.

Summary

  • A class describes data plus behavior; a class variable is a reference to a heap object.
  • Create an object, then try, and free it in finally.
  • Assignment copies the reference, so aliases share one object; nil means no object.
  • The creator (or a designated owner) must free the object; override Destroy to free owned parts.
  • Use records for small values and classes when identity, sharing or inheritance matter.

Next: Properties and Visibility