Skip to content

Commit 61bbae3

Browse files
committed
Add callbacks_of_object_class_methods.dpr and check compilation of it
1 parent 4099c15 commit 61bbae3

File tree

3 files changed

+35
-16
lines changed

3 files changed

+35
-16
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ modern_pascal_introduction_ukrainian.xml
3838
/code-samples*/anon_functions_assignment_test
3939
/code-samples*/callbacks
4040
/code-samples*/callbacks_of_object
41+
/code-samples*/callbacks_of_object_class_methods
4142
/code-samples*/class_properties
4243
/code-samples*/constructor_destructor
4344
/code-samples*/exception_finally
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}
2+
{$ifdef MSWINDOWS} {$apptype CONSOLE} {$endif}
3+
4+
type
5+
TMyMethod = function (const A, B: Integer): Integer of object;
6+
7+
TMyClass = class
8+
class function Add(const A, B: Integer): Integer;
9+
class function Multiply(const A, B: Integer): Integer;
10+
end;
11+
12+
class function TMyClass.Add(const A, B: Integer): Integer;
13+
begin
14+
Result := A + B;
15+
end;
16+
17+
class function TMyClass.Multiply(const A, B: Integer): Integer;
18+
begin
19+
Result := A * B;
20+
end;
21+
22+
var
23+
M: TMyMethod;
24+
begin
25+
{$ifdef FPC}
26+
// Unfortunately, this requires a bit of hack to work in FPC ObjFpc mode.
27+
M := @TMyClass(nil).Add;
28+
M := @TMyClass(nil).Multiply;
29+
{$else}
30+
M := TMyClass.Add;
31+
M := TMyClass.Multiply;
32+
{$endif}
33+
end.

modern_pascal_introduction.adoc

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2054,23 +2054,8 @@ Note that you _cannot_ pass global procedures / functions as methods. They are i
20542054
+
20552055
[source,pascal]
20562056
----
2057-
type
2058-
TMyMethod = function (const A, B: Integer): Integer of object;
2059-
2060-
TMyClass = class
2061-
class function Add(const A, B: Integer): Integer
2062-
class function Multiply(const A, B: Integer): Integer
2063-
end;
2064-
2065-
var
2066-
M: TMyMethod;
2067-
begin
2068-
M := @TMyClass(nil).Add;
2069-
M := @TMyClass(nil).Multiply;
2070-
end;
2057+
include::code-samples/callbacks_of_object_class_methods.dpr[]
20712058
----
2072-
+
2073-
Unfortunately, you need to write ugly `@TMyClass(nil).Add` instead of just `@TMyClass.Add`.
20742059

20752060
* A (possibly) local routine: declare with `is nested` at the end, and make sure to use `{$modeswitch nestedprocvars}` directive for the code. These go hand-in-hand with <<Local (nested) routines>>.
20762061

0 commit comments

Comments
 (0)