Sign in Join
Wiki copytemporary

Object Oriented Programming with Free Pascal and Lazarus: what changed

Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11## Introduction
22
33There are many excellent tutorials about Pascal, but this tutorial attempts to take the beginner further, into [[Glossary|Object-Oriented Programming]] with [[Object Pascal]], which is an extension to standard [[Pascal]], offered by [[Turbo Pascal]], [[Delphi]] and [[Free Pascal]] / [[Lazarus]].
44
55An [[Glossary|Object]] is an extension of the standard Pascal [record](http://wiki.lazarus.freepascal.org/Record) structure
66
77Standard text-based Pascal programming is good for creating applications which, like traditional Unix applications, do one thing and do it very well. The 'one thing' that a program does might be a very complicated action, and might offer the user several menu-driven options, but it is essentially restricted to obeying commands that the user types at the keyboard and listing its responses on the terminal or a printer.
88
99In order to provide a [[Glossary|Graphical User Interface (GUI)]] it is usual to invoke some sort of Object-Oriented Programming method (often making use of [[Glossary|C]] or one of its variants, or Visual Basic, or one of the [[Glossary|OO]] variants of Pascal such as [[Glossary|Free Pascal]] with or without [[Glossary|Lazarus]]).
1010
1111In a GUI the user is presented with a screen with a large number of images arranged in a structured way, consisting of a set of tools or [[Glossary|Widgets]] that are associated with various actions such as
1212
1313- selecting from a menu,
1414- opening or saving files,
1515- connecting to the Internet,
1616- performing numerical computations, etc.
1717
1818The user is expected to move a mouse or other pointer/selection tool over the screen, to select actions which are to be performed in response to a mouse button click or a key-press.
1919
2020While systems to deal with a complex graphical user interface could be written in standard Pascal or almost any other programming language, it is much easier to use an object-oriented system, in which each graphical object on the screen can have all its properties and the procedures and functions associated with its use kept together in a common structure.
2121
2222## Objects - a real-world analogy
2323
2424Consider the analogy of a blood sample collected in a hospital or a doctor's office.
2525
2626### Blood Sample
2727
2828The physical sample is certainly an **object**; it has, associated with it, a lot of information, documents and other physical objects.
2929
3030- **Sample tube**, of a type determined by the test that the physician wants performed.
3131
3232- **Local rule** (or *method*, *standard operating procedure*) to direct the nurse or technician collecting the sample
3333 - which type of tube to use,
3434 - how to process the sample
3535 - how to store it before transfer to the lab.
3636
3737- **Label** on the tube with details of the
3838 - sample identifier
3939 - patient's name and birthdate
4040 - date and time of collection
4141 - tests required.
4242
4343- **Request form** that accompanies the sample to the lab, directing
4444 - sample ID
4545 - ID of requesting physician
4646 - what test the physician requests and
4747 - giving fuller details of the patient
4848 - the possible diagnosis for which confirmation is sought.
4949
5050A copy of the request form is placed in the patient's notes, to remind the physician to expect results within an appropriate time.
5151
5252- In the lab - **local methods** to determine
5353 - how the sample is to be analysed,
5454 - what machines to use,
5555 - how the machines are to be calibrated and operated,
5656 - how the results are to be stored, formatted and
5757 - reported back to the physician.
5858
5959The actual **results** are a record that the physician uses to assist the diagnosis, and a copy of the results is filed in the patient notes.
6060
6161The physical sample might be retained for reference, confirmation or further tests, or might be disposed of by pouring down the sink or by incineration; there will be a method to describe this.
6262
6363There is no need for a physician to spell out all the details and instructions every time a sample is collected; indeed, he may have very little knowledge of how the sample is processed in the lab. The details of the various processes are **inherited** from previous sample collections and analyses - there will be a generic plan for the whole sequence, and together we could think of the blood sample, all its documents and data, and the underlying methods, as a complex **object**.
6464
6565In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.
6666
6767### Another Example - Automobile
6868
6969If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair. It might consist of:
7070
7171- the physical vehicle
7272- documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc
7373- the fuel consumption history
7474- the drivers allowed to use the vehicle, with their license particulars
7575- service records held by the garage
7676- methods or procedures to be followed for routine checking and maintenance
7777- methods to be followed for non-routine repairs etc
7878- billing information for the customer
7979
8080## Programming Example
8181
8282Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in [[Object Pascal]].
8383
8484Let us consider the creation of a simple Form with a few controls for an application in Free Pascal/Lazarus.
8585
86-<div class="floatleft">
87-
88-<figure>
89-<img src="ObjectInspector-TForm.png" title="ObjectInspector-TForm.png" />
90-<figcaption>ObjectInspector-TForm.png</figcaption>
91-</figure>
92-
93-</div>
94-
95-<div class="floatright">
96-
97-<figure>
98-<img src="BlankForm.png" title="BlankForm.png" />
99-<figcaption>BlankForm.png</figcaption>
100-</figure>
86+![](/wiki-images/2/25/ObjectInspector-TForm.png)
10187
102-</div>
88+![](/wiki-images/e/e2/BlankForm.png)
10389
10490On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.
10591
10692Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.
10793
10894------------------------------------------------------------------------
10995
11096If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window.
11197
11298Several of the properties have names similar to those for the Form; this is because many properties are **Inherited** from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes.
11399
114100As well as properties, the Object Inspector offers a tab called **Events**, which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).
115101
116102The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or **Object** in Pascal.
117103
118-<div class="floatleft">
119-
120-<figure>
121-<img src="ObjectInspector-TButton.png" title="ObjectInspector-TButton.png" />
122-<figcaption>ObjectInspector-TButton.png</figcaption>
123-</figure>
124-
125-</div>
126-
127-<div class="floatright">
128-
129-<figure>
130-<img src="FormWithButton.png" title="FormWithButton.png" />
131-<figcaption>FormWithButton.png</figcaption>
132-</figure>
133-
134-</div>
135-
136-<div class="floatright">
104+![](/wiki-images/f/f5/ObjectInspector-TButton.png)
137105
138-<figure>
139-<img src="Source_FormWithButton1.png‎" title="Source_FormWithButton1.png‎" />
140-<figcaption>Source_FormWithButton1.png‎</figcaption>
141-</figure>
106+![](/wiki-images/e/e8/FormWithButton.png)
142107
143-</div>
108+![](/wiki-images/4/4d/Source_FormWithButton1.png%E2%80%8E)
144109
145110## Object-Oriented Extensions to standard Pascal
146111
147112The Pascal record structure is extended by defining an
148113
149114### Object
150115
151116An Object is a special kind of record. The record contains all the fields that are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type.
152117
153118For example, an object could contain an array of real values, together with a Method for calculating the average.
154119
155120``` pascal
156121Type
157122 Average = Object
158123 NumVal: Integer;
159124 Values: Array [1..200] of Real;
160125 Function Mean: Real; { calculates the average value of the array }
161126 End;
162127```
163128
164129Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.
165130
166131Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared as public, protected or private. By default, fields and methods are public, and can be exported outside the current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit: their scope is limited to the implementation of the current unit.
167132
168133### Class
169134
170135Objects are not used very often by themselves in Free Pascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.
171136
172137Here is a simple example of a typical Class declaration:
173138
174139``` pascal
175140{-------------------------------------------}
176141{ Example of Class declaration from the LCL }
177142{-------------------------------------------}
178143 TPen = class(TFPCustomPen)
179144 private
180145 FColor: TColor;
181146 FPenHandleCached: boolean;
182147 FReference: TWSPenReference;
183148 procedure FreeReference;
184149 function GetHandle: HPEN;
185150 function GetReference: TWSPenReference;
186151 procedure ReferenceNeeded;
187152 procedure SetHandle(const Value: HPEN);
188153 protected
189154 procedure DoAllocateResources; override;
190155 procedure DoDeAllocateResources; override;
191156 procedure DoCopyProps(From: TFPCanvasHelper); override;
192157 procedure SetColor
193158 (const NewColor: TColor; const NewFPColor: TFPColor); virtual;
194159 procedure SetFPColor(const AValue: TFPColor); override;
195160 procedure SetColor(Value: TColor);
196161 procedure SetMode(Value: TPenMode); override;
197162 procedure SetStyle(Value: TPenStyle); override;
198163 procedure SetWidth(value: Integer); override;
199164 public
200165 constructor Create; override;
201166 destructor Destroy; override;
202167 procedure Assign(Source: TPersistent); override;
203168 property Handle: HPEN read GetHandle write SetHandle; deprecated;
204169 property Reference: TWSPenReference read GetReference;
205170 published
206171 property Color: TColor read FColor write SetColor default clBlack;
207172 property Mode default pmCopy;
208173 property Style default psSolid;
209174 property Width default 1;
210175 end;
211176```
212177
213178Note that this class is defined as an instance of another **parent** or **ancestor** class (*TFPCustomPen*) from which it **inherits** all its properties and methods. It has some fields of its own, grouped under
214179
215180- **private** - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from *Graphics*, so any of the other classes such as *TBitMap*, *TPicture* etc in the same unit can use them). They are essentially local variables (eg *FColor*, *FPenHandleCached*) or locally used methods (*GetHandle*, *SetHandle*) but can be used or referred to in items declared in the **protected** or **public** sections.
216181- **protected** - this means that items defined here are only available or visible to classes that are descended from this **ancestor** class, and inherit its properties or methods
217182- **public** - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary|Uses]] clause
218183- **published** - is the same as a **public** section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no **published** list, all the **public** fields usually appear in the Object Inspector.
219184
220185### Methods
221186
222187A method is just like a standard procedure or function, but can have some additional **directives**.
223188
224189Some of the methods defined above are labelled with the directive **virtual**; others are labelled with the **override** directive.
225190
226191- **virtual** means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.
227192- **override** means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was **virtual**. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the **inherited** clause.
228193
229194Methods with no virtual or override directive are **static** methods (the usual kind in Pascal). Those with a virtual or override directive are **dynamic**.
230195
231196Special instances of methods are:
232197
233198- **create** - a **constructor** for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.
234199- **destroy** - a **destructor** for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.
235200
236201### Properties
237202
238203Properties are just like ordinary fields in a conventional Pascal record, but they can have **read** and/or **write** specifiers.
239204
240205- **read** specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property *Color* has a read specifier *FColor*, which is a local variable containing the value to be used. If a property has a **read** but no **write** specifier, it is read-only.
241206- **write** specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, *Color* has a write specifier *SetColor* that is a procedure (defined in the **protected** section) for writing the color value to some specified location. If a property has a **write** but no **read** specifier, it is write-only.
242207- **default** - note that it is possible to set a **default** value for a property. For example, *Color* here is given the default value *clBlack*, or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.
243208- **index** specifier is an integer that the **read** or **write** methods, shared between properties, can use to identify which property is desired. Note that if **index** is used the **read** or **write** specifiers must be a function or a procedure respectively and cannot be a normal field/variable.
244209
245210#### Examples
246211
247212``` pascal
248213 TFooClass = class
249214 private
250215 FIntProp: Integer;
251216 public
252217 property IntProp: Integer read FIntProp write FIntProp;
253218 end;
254219```
255220
256221``` pascal
257222 TFooClass = class
258223 private
259224 function GetListProp(AIndex: Integer): String;
260225 procedure SetListProp(AIndex: Integer; AValue: String);
261226 public
262227 // this type of property may not be in the published section of a class
263228 property ListProp[AIndex: Integer]: String read GetListProp write SetListProp;
264229 end;
265230```
266231
267232``` pascal
268233 TFooClass = class
269234 private
270235 function GetValue(const AIndex: Integer): Integer;
271236 procedure SetValue(const AIndex: Integer; AValue: Integer);
272237 public
273238 // note that the read and write methods are shared
274239 property Value1: Integer index 1 read GetValue write SetValue;
275240 property Value2: Integer index 2 read GetValue write SetValue;
276241 property Value3: Integer index 3 read GetValue write SetValue;
277242 property Value4: Integer index 4 read GetValue write SetValue;
278243 // index may be a const or a number or you can even use an enumerated type
279244 // for example:
280245 // property Value: Integer index ord(seSomeEnum) read SomeFunction write SomeProcedure;
281246 end;
282247```
283248
284249## Free Pascal Language Extensions
285250
286251FPC includes several language extensions to its "standard" Pascal syntax to support object oriented programming.
287252
288253- Objects (chapter 5) [[Programming Using Objects]]
289254- Classes (chapter 6) [[Programming Using Classes]]
290255- Interfaces (chapter 7) [[Programming Using Interfaces]]
291256- Generics (chapter 8) [[Programming Using Generics]]
292257
293258These extensions are described in the indicated chapters of the FPC Language Reference Guide: <http://www.freepascal.org/docs.var>. Links to tutorial pages for each concept are included above as well. The Language Reference Guide includes syntax diagrams and further details not contained in this introductory tutorial. Of the four language features listed above, **Objects** and **Classes** form the basis of object oriented programming (OOP) in FPC and Lazarus. For those new to OOP, the **Objects** section includes more introductory concepts and the **Classes** section minimizes repetition by emphasizing the similarities and differences to the **Objects** syntax. In general, the **Classes** implementation seems to be more widely in use including Delphi Lazarus developers. Often the word "objects" is used to refer to what is actually a "class" in the **Classes** dialect of OOP in FPC. These documents will be worded to minimize any terminology confusion, but outside of this document, the term "object" oftentimes refers to objects created from a **Class**. In fact, the FPC run time library (RTL) includes a class library with a base **class** called *TObject*.
294259
295260Users familiar with the older Turbo Pascal OOP implementation may initially want to skip the section on Classes since the Objects implementation is based on the older Turbo Pascal dialect. The section on **Classes** should be familiar to Delphi users since it is based on Delphi syntax. Be aware that some of the writeup in the **Classes** section may refer to concepts from the **Objects** section. For Macintosh developers familiar with the various Apple, THINK and MPW Object Pascal dialects, neither the FPC Objects or Classes dialects provide a direct migration path. As of March 2009, there are discussions on the Mac Pascal Mailing list about potentially providing some compiler support (new syntax) for accessing Apple's Objective C / Cocoa framework.
296261
297262### General Concepts of Object Oriented Pascal
298263
299264OOP provides different ways to manage and encapsulate data and to manage program flow compared with other available programming language features and constructs. OOP often lends itself to modeling certain applications such as Graphic User Interfaces (GUI's) and physical systems in a more natural feeling manner. However OOP is not appropriate for all applications. Program control is not as explicit as the more basic Pascal procedural constructs. To obtain the most benefit from OOP, understanding of large class libraries is often required which can entail a steep learning curve. Maintaining large OOP application code has its advantages and disadvantages compared to maintaining strictly procedural code. There are many sources for learning OO analysis, design and programming techniques which are beyond the scope of this guide.
300265
301266There are numerous programming languages which incorporate OOP features as extensions or the basis of their language. As such, there are many different terms for describing OO concepts. Even within FPC, some of the terminology overlaps. In general, OOP usually consists of the concept of a programming object (or information unit) which explicitly combines and encapsulates a related set of data and procedures which act on the data. This data is usually persistent during program execution but with mechanisms to reduce some of the problems inherent in declaring global variables. In addition, OOP languages enable objects to be incrementally modified and/or extended based on previously defined objects. This feature is usually referred to by the terms *inheritance* and *polymorphism*. Many OOP languages use the terms *method* or *message* referring to procedures which belong to an object. Much of the power of OOP is realized by late (run time) dynamic binding of methods rather than compile binding. This dynamic binding of methods is similar to using procedural variables and procedural parameters but with greater syntactic cohesion, encapsulation with the data it is related to and also inheritance of behavior of previously defined methods. The following wiki pages provide a starting point for discovering more about analysis, design and programming in an object orient manner.
302267
303268## Further information
304269
305270This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [Free Pascal](http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html) manuals, especially Chapters 5 (**Objects**) and 6 (**Classes**)
306271
307272Borland was also kind enough to release the Object Oriented Programming chapter from the original Turbo Pascal manuals in PDF form. This chapter is from when Borland introduced this new language feature into Turbo Pascal. The chapter might be old, but the OOP theory is still very relevant today. You can download a copy from the following [link](http://geldenhuys.co.uk/articles/) under the "Other" category.
308273
309274## See also
310275
311276- [[Programming Using Classes]]
312277- [[Free Pascal videos|Free Pascal video tutorials]]
313278- [[Lazarus videos|Lazarus video tutorials]]
314279- [[Pascal and Lazarus Books and Magazines]]
315280
316281## External Links
317282
318283- <https://castle-engine.io/modern_pascal_introduction.html> - FPC mode ObjFPC
319284- <http://newpascal.org/assets/modern_pascal_introduction.html> - FPC mode Delphi
320285
321286- <http://en.wikipedia.org/wiki/Object-oriented_programming>
322287- <http://en.wikipedia.org/wiki/OOAD>
323288- <http://en.wikipedia.org/wiki/Object_oriented_design>
324289
325290---
326291*From the Free Pascal wiki, page "Object Oriented Programming with Free Pascal and Lazarus", as it stood on 2021-04-14 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history