What are published class properties in Pascal?
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
information for the methods, fields, and properties in theRTTI Run Time Type Information publishedsection. This information is needed for automatic streaming.The
publishedspecifier can be used within classes only, not interfaces.The fields defined in the
publishedsection must be of the ordinal type, real type, strings, or sets. They cannot be arrays.A class can only contain a
publishedsection if compiled in$M+mode.
Let's go over the following example to get a grasp on this subject:
Code example
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.
Code explanation
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
publishedsection.Lines 4–7: Define a class called
myClassusing theClasskeyword. Include apublishedsection within this class containing a member function namedmyFirstFunc.Lines 9–12: Define the previously declared
myFirstFuncfunction. This function returns an integer value.Lines 13–14: Declare a variable named
cl1with themyClasstype.Line 17: Create an instance of the
myClassclass and store it in the previously declaredcl1variable.Line 18: Using this class instance, invoke the
myFirstFuncfunction
and print out its result.
Free Resources