DMarlon Studio

Lesson 1 · 1 of 20

Classes and objects · Pascal

Declare Object Pascal classes with fields, methods, a constructor and a destructor, and learn to release objects with Free in Free Pascal.

Pascal · Classes and objects in DMarlon Studio: the example's code and its output in the terminal

A class groups data with the code that works on it. TCustomer declares two fields (Name and Orders) and three methods. With no visibility section, everything is public. Each method body is written afterwards, outside the class, under its full name: TCustomer.AddOrder.

The constructor Create allocates the object, fills it with zeros (that is why Orders starts at 0 without any code) and then runs its own body: it stores the name and prints Created Ana Lopez. You call it on the class: TCustomer.Create('Ana Lopez').

The destructor Destroy is marked override because it replaces the one in TObject, the root of every class, and it ends with inherited Destroy so the memory is actually released. You never call it directly: you call `Free`, which first checks the variable is not nil and then calls Destroy.

A class variable is a reference, not the object itself. other := ana does not copy the customer: both variables point to the same object, so both AddOrder calls bump the same counter and the output says 2 orders. Unlike the records from the basic course, assignment duplicates nothing.

For the same reason, the object is freed exactly once. After ana.Free, other points to released memory and must not be used. This create, use and free pattern is the heart of every desktop app DMarlon Studio builds with Lazarus.

Code · main.pas

program main;type  TCustomer = class    Name: String;    Orders: Integer;    constructor Create(const AName: String);    destructor Destroy; override;    procedure AddOrder;  end;constructor TCustomer.Create(const AName: String);begin  Name := AName;  // Orders already starts at 0  WriteLn('Created ', Name);end;destructor TCustomer.Destroy;begin  WriteLn('Freed ', Name);  inherited Destroy;end;procedure TCustomer.AddOrder;begin  Inc(Orders);end;var ana, other: TCustomer;begin  ana := TCustomer.Create('Ana Lopez');  ana.AddOrder;  other := ana;  // copies the reference: still one single object  other.AddOrder;  WriteLn(ana.Name, ' has ', ana.Orders, ' orders');  ana.Free;      // free it once; other now points to freed memoryend.

Output · fpc main.pas && ./main

Created Ana Lopez
Ana Lopez has 2 orders
Freed Ana Lopez

Key points

  • A class declares fields and methods; method bodies go separately.
  • Create allocates the object and zeroes its fields.
  • A destructor is marked override and ends with inherited Destroy.
  • Release objects with Free, never by calling Destroy.
  • Assigning an object copies the reference, not the object.

Exercise

Add a Total: Double field to TCustomer and an AddOrder(amount: Double) method that adds the amount, then print Ana's total after two orders of 25.50 and 14.99.