Description |
The Object keyword has one principle use - to qualify a function or procedure data type, allowing it to refer to an equivalent object method.
The older, obsolete use (not given in the syntax above), was used to create an object (now we use a class constructor).
Variables of function and procedure types can be used as pointers, in effect, to functions and procedures with the same argument and return value profile (signature).
For example :
function AddUp(a, b : Integer) : Integer;
...
type
TFunc = function(a, b : Integer) : Integer;
var
func : TFunc;
c : Integer;
begin
func := AddUp;
c := func(12, 34); // Invokes AddUp function
end;
With the Of Object qualifier, the subroutine type must be set to refer to a method in an object. For example :
type
TMyClass = class
public
procedure StoreName(name : string);
end;
TProc = procedure(name : string) of Object;
var
proc : TProc;
myClass : TMyClass;
begin
myClass := TMyClass.Create;
proc := myClass.StoreName;
proc('My name'); // Invokes myClass.StoreName
end;
|
|
Notes |
Such subroutine types are in effect pointers to both the code and data parts of the method.
|
|
Related commands |
Class |
|
Starts the declaration of a type of object class |
Function |
|
Defines a subroutine that returns a value |
Procedure |
|
Defines a subroutine that does not return a value |
TObject |
|
The base class type that is ancestor to all other classes |
|
|
|
Example code : Accessing an object method directly and indirectly |
// Full Unit code. // ----------------------------------------------------------- // You must store this code in a unit called Unit1 with a form // called Form1 that has an OnCreate event called FormCreate.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type // Define a simple class
TSimple = class
private
name : string;
public
function GetName : string;
constructor Create(name : string);
end;
// The form class itself
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
// Create a simple object
constructor TSimple.Create(name: string);
begin // Save the passed string
self.name := name;
end;
// Returns the simple name
function TSimple.GetName: string;
begin
Result := name;
end;
// Main line code
procedure TForm1.FormCreate(Sender: TObject);
type
TNameFunc = Function : string of Object;
var
simple : TSimple;
nameFunc : TNameFunc;
begin // Create a simple object
simple := TSimple.Create('Brian');
// Show the object name
WriteLn('Name accessed directly = '+simple.GetName);
// Now refer to this method indirectly
nameFunc := simple.GetName;
// Show the object name
WriteLn('Name accessed indirectly = '+nameFunc);
end;
end.
|
Name accessed directly = Brian
Name accessed indirectly = Brian
|
|