Class, Class Instance, Constructor, Destructor
The example above includes TAnimal and its subclass TDog. A class is merely a type, which can be understood as a template. The class itself does not store any data, and no memory will be allocated for the field MyInt: Integer in the example.
Although class variables allow the class itself to hold data, we will not cover this for now and only discuss regular classes with ordinary fields.
To allocate memory for fields, you must create a class instance; creating an instance requires calling a constructor.
If you never instantiate a class, its code is effectively non-existent—it will never run, and no memory will be allocated for its variables. Think of a class like a mold: memory is only allocated when you use it. When unused, it simply sits idle with no resource consumption.
Constructor
- A special method declared with the keyword
constructor; - The system allocates memory for the object first before executing the constructor code;
- All classes implicitly inherit from
TObjectand come with a parameterless constructorCreate, which works even without manual definition; - Custom constructors are the best way to initialize objects, allowing you to assign initial values to fields within the constructor;
- Custom constructors are conventionally named
Create.
Example
program Demo;
{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}
{$ifdef MSWINDOWS} {$apptype CONSOLE} {$endif}
{$codepage utf8}
uses SysUtils;
type
TAnimal = class
private
InternalStuff: TObject;
public
constructor Create;
destructor Destroy; override;
end;
constructor TAnimal.Create;
begin
inherited Create; // Call parent constructor first
InternalStuff := TObject.Create;
Writeln('Execute TAnimal.Create constructor');
end;
destructor TAnimal.Destroy;
begin
Writeln('Execute TAnimal.Destroy destructor');
FreeAndNil(InternalStuff); // Release internal child object
inherited Destroy; // Call parent destructor at the end
end;
var
C: TAnimal;
begin
C := TAnimal.Create;
try
// Use object
finally
FreeAndNil(C); // Automatically invoke Destroy destructor
end;
end.
Execution Output
D:\fpcdemo>fpc mydemo.dpr
Free Pascal Compiler version 3.2.2 [2021/05/15] for i386
Copyright (c) 1993-2021 by Florian Klaempfl and others
Target OS: Win32 for i386
Compiling mydemo.dpr
Linking mydemo.exe
38 lines compiled, 0.1 sec, 68672 bytes code, 4260 bytes data
D:\fpcdemo>mydemo
Execute TMyClass.Create constructor
Execute TMyClass.Destroy destructorCode language: CSS (css)
InternalStuff is a child object held internally by the class. It is created in the constructor and must be released via FreeAndNil in the destructor to prevent memory leaks.
