In Pascal, a class declaration may include multiple private, protected, published, and public blocks as required. The visibility of these blocks differs depending on the selected access modifier.
Typically, the published
access modifier is nearly similar to the public
modifier and it has the following characteristics:
Denotes a section within a class that is accessible from any place.
The compiler generates published
section. This information is needed for automatic streaming.
The published
specifier can be used within classes only, not interfaces.
The fields defined in the published
section must be of the ordinal type, real type, strings, or sets. They cannot be arrays.
A class can only contain a published
section if compiled in $M+
mode.
Let's go over the following example to get a grasp on this subject:
This example shows how to declare a class containing a published
section:
program hello;{$mode objfpc}{$M+}typemyClass = ClasspublishedFunction myFirstFunc : Integer;end;Function myClass.myFirstFunc : Integer;beginResult := 5;end;varcl1 : myClass;beginwriteln('Start...');cl1:=myClass.create;writeln('cl1.myFirstFunc = ',cl1.myFirstFunc());writeln('End...');end.
Let's go over the code widget above:
Line 1: Refer to the program header. It is used for backward compatibility, and it is ignored by the compiler.
Line 2: Directives to the compiler to allow defining classes containing a published
section.
Lines 4–7: Define a class called myClass
using the Class
keyword. Include a published
section within this class containing a member function named myFirstFunc
.
Lines 9–12: Define the previously declared myFirstFunc
function. This function returns an integer value.
Lines 13–14: Declare a variable named cl1
with the myClass
type.
Line 17: Create an instance of the myClass
class and store it in the previously declared cl1
variable.
Line 18: Using this class instance, invoke the myFirstFunc
function
and print out its result.