Classes and Objects
15.1 Declaring a Class
type
TBankAccount = class
private
FOwner: string;
FBalance: Currency;
FTransactions: TStringList;
public
constructor Create(const AOwner: string; AInitial: Currency = 0);
destructor Destroy; override;
procedure Deposit(Amount: Currency);
function Withdraw(Amount: Currency): Boolean;
function ToString: string; override;
property Owner: string read FOwner;
property Balance: Currency read FBalance;
end;
constructor TBankAccount.Create(const AOwner: string; AInitial: Currency);
begin
inherited Create; // call TObject.Create
FOwner := AOwner;
FTransactions := TStringList.Create;
if AInitial > 0 then Deposit(AInitial);
end;
destructor TBankAccount.Destroy;
begin
FTransactions.Free; // free owned objects
inherited; // ALWAYS call inherited last in destructors
end;
procedure TBankAccount.Deposit(Amount: Currency);
begin
if Amount <= 0 then raise EArgumentException.Create('Amount must be positive');
FBalance := FBalance + Amount;
FTransactions.Add(Format('Deposit %m', [Amount]));
end;
function TBankAccount.Withdraw(Amount: Currency): Boolean;
begin
Result := Amount <= FB
…15.2 Creating and Freeing Objects
Class instances are references (pointers) to heap objects. Variables default to garbage (locals) or nil (fields/globals).
Manual memory management applies on all platforms (ARC was removed in 10.4). Every Create needs a matching Free (or an owner, or interface reference counting).
var Acc := TBankAccount.Create('Ana', 500);
try
Acc.Deposit(250);
if not Acc.Withdraw(1000) then Writeln('Insufficient funds');
Writeln(Acc.ToString);
finally
Acc.Free; // Free calls Destroy if the object isn't nil
end;
FreeAndNil(Obj); // free and set the variable to nil15.3 TObject: The Root Class
Methods: Create, Destroy, Free, ClassName, ClassType, ClassParent, InheritsFrom, Equals, GetHashCode, ToString, AfterConstruction, BeforeDestruction, FieldAddress, MethodAddress, InstanceSize.
15.4 Self, inherited and Class Completion
Self is the current instance. inherited calls the parent implementation (inherited; with the same parameters, or inherited Create(X)).
Class Completion (Ctrl+Shift+C) generates method bodies and property fields automatically.