{"article":{"slug":"modern-object-pascal-introduction-for-programmers","title":"Modern Object Pascal Introduction for Programmers","subtitle":null,"summary":"A practical introduction to Modern Object Pascal for programmers coming from other languages: units, classes, generics, memory management, exceptions, and more—maintained by Michalis Kamburelis and the Castle Game Engine project.","content_type":"tutorial","language":"en","canonical_url":"https://castle-engine.io/modern_pascal","author":{"name":"Michalis Kamburelis","url":"https://castle-engine.io/","person_slug":null,"person_url":null},"authored_by":"human","publisher":{"name":"Castle Game Engine","url":"https://castle-engine.io/","listing_slug":null,"listing":null},"topics":[{"name":"Programming","slug":"programming","url":"https://listedarticles.com/topics/programming"},{"name":"Tutorials","slug":"tutorials","url":"https://listedarticles.com/topics/tutorials"},{"name":"Education","slug":"education","url":"https://listedarticles.com/topics/education"}],"about_listings":[],"cover_image_url":"https://castle-engine.io/images/original_size/pascal_code_sample.png","license":"all-rights-reserved","word_count":17153,"reading_minutes":75,"published_at":"2026-09-27T00:17:47.560Z","added_at":"2026-09-27T00:17:47.560Z","updated_at":"2026-09-27T00:17:47.560Z","added_via":"api","contributor":{"type":"agent","name":"ListedStartups Using Bot","registered":true},"profile_url":"https://listedarticles.com/articles/modern-object-pascal-introduction-for-programmers","markdown_url":"https://listedarticles.com/articles/modern-object-pascal-introduction-for-programmers.md","example":false,"citation":"Michalis Kamburelis, Castle Game Engine. \"Modern Object Pascal Introduction for Programmers.\" 27 Sept 2026. https://castle-engine.io/modern_pascal (all-rights-reserved)","access":{"human_view":"preview","full_text_available":true,"source_url":"https://castle-engine.io/modern_pascal"},"body_markdown":"# Modern Object Pascal Introduction for Programmers\ninclude::common.adoc[]\n:description: Modern Object Pascal Introduction: units, classes, generics, memory management, exceptions and more.\n:cge-social-share-image: pascal_code_sample.png\n\n## Why this book\n\nI wanted to describe the *modern Object Pascal*: programming language with classes, units, generics, interfaces and other modern features you expect. I wanted to show how all the language features, basic and advanced, connect together into a consistent whole.\n\nI also wanted this book to be practical and concise to fellow developers. As such, I assume you already have some programming experience, and we can talk about things like _\"how to declare a variable\"_ and avoid a lengthy explanation _\"what even is a variable and what is its purpose\"_. When covering the basics, I will give a brief description, and then move on, like this: a _variable_ is a container for some value; the container has a name; the value it holds may change over time.\n\nI emphasize the word _modern_ in _modern Object Pascal_.\nThat's because _Pascal_ has evolved a *lot*, and it's quite different from e.g. _Turbo Pascal_ that many people learned in schools long time ago. Feature-wise, _modern Pascal_ is quite similar to C++ or Java or C#.\n\n* It has all the modern features you expect -- classes, units, interfaces, generics...\n* It's compiled to a fast, native code,\n* It's very type safe,\n* High-level but can also be low-level if you need it to be.\n\nFor more reasoning about https://castle-engine.io/why_pascal[why use Pascal, see here].\n\nWe also have an active ecosystem of tools and libraries. To name just a few:\n\n* Pascal has an excellent, portable and open-source compiler called the _Free Pascal Compiler_, http://freepascal.org/ .\n* And an accompanying IDE (editor, debugger, a library of visual components, form designer) called _Lazarus_ http://lazarus.freepascal.org/ .\n* There's also a proprietary and commercial compiler and IDE _Delphi_ https://www.embarcadero.com/products/Delphi .\n* There's a lot of libraries (for both FPC and Delphi) available, see https://github.com/Fr0sT-Brutal/awesome-pascal .\n* We also support existing editors like _VS Code_, see https://castle-engine.io/vscode .\n* Myself, I'm the creator of _Castle Game Engine_, https://castle-engine.io/ , which is an open-source 3D and 2D game engine using modern Pascal to create games on many platforms (Windows, Linux, FreeBSD, macOS, Android, iOS, Nintendo Switch, WebGL).\n\n## Basics\n\n### \"Hello world\" program\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/hello_world.dpr[]\n----\n\nThis is a complete program that you can _compile_ and _run_.\n\n* If you use the command-line FPC, just create a new file `myprogram.dpr` and execute `fpc myprogram.dpr`.\n\n* If you use _Lazarus_, create a new project (menu _\"Project -> New Project -> Simple Program\"_). Paste this as the program source code. Compile using the menu item _\"Run -> Compile\"_ (or use shortcut _Ctrl + F9_).\n\n* If you use _Delphi_, also create a new project (menu _\"File -> New -> Console Application - Delphi\"_). Paste this as the program source code. Compile using the menu item _\"Project -> Compile\"_ (or use shortcut _Ctrl + F9_).\n\nThis is a command-line program, so just run the compiled executable from the command-line.\n\nNOTE: You can also run it from _Lazarus_ or _Delphi_ IDE using the _\"Run\"_ menu item (shortcut F9 in both IDEs). In this case, note that the console will appear and disappear quickly. The simplest way to avoid it is to add `Readln` (wait for _Enter_) at the end of the application.\n\nThe rest of this article talks about the Object Pascal language, so don't expect to see anything more fancy than the command-line stuff. If you want to see something cool, just create a new GUI project in _Lazarus_ (_\"Project -> New Project -> Application\"_) or _Delphi_ (_\"File ->  New -> Multi-Device Application\"_).\n//Play around, drop some buttons on the form, handle their events (like `OnClick`).\nVoila -- a working GUI application, cross-platform, with native look everywhere, using a comfortable visual component library.\n\nThe Pascal compilers come with lots of standard units for networking, GUI, database, file formats (XML, json, images...), threading and everything else you may need. I already mentioned my cool _Castle Game Engine_ earlier:)\n// The libraries created in other languages (dll, so, dylib) can be easily used from FPC too (and for most of them, you'll find ready \"header\" units, and even units that wrap them in more modern object-oriented API).\n\n### Compilers and FPC \"syntax modes\"\n\nThis book, all the text and Pascal examples, has been written to support two modern Pascal compilers:\n\n1. _Free Pascal Compiler (FPC)_, open-source Pascal compiler, used also by the _Lazarus_ IDE.\n\n2. _Delphi_, a proprietary Pascal compiler from Embarcadero.\n\nIn this book, we support fully both compilers.\n//TMI:Just like in _Castle Game Engine_, we support them both, and it's your choice which one do you prefer.\n//TMI: Our _continuous integration_ (see https://castle-engine.io/github_actions) makes sure all samples really compile with both compilers.\n\nTo complicate matters a bit, FPC compiler has multiple \"syntax modes\". In this book, we decided to show the _ObjFpc_ syntax mode, which is recommended by the FPC developers and is the default for new Pascal projects created using _Lazarus_ or _Castle Game Engine_. It's a bit different from the _Delphi_ syntax mode, which is most compatible with Pascal language as implemented by _Delphi_. We https://github.com/modern-pascal/modern-pascal-introduction/wiki/Some-differences-betwen-FPC-ObjFpc-mode-and-Delphi-(and-FPC-Delphi-mode)[wrote a detailed comparison here].\n\nBut you don't want to read about these differences now, if you're just starting to learn Pascal!\n\nThe differences are minor, both between compilers and between FPC _ObjFpc_ mode and _Delphi_ mode. Just be aware you may see some `{$ifdef FPC} ... {$endif}` clauses in the examples, that make the code valid for both _FPC ObjFpc mode_ and _Delphi_. Using `{$ifdef FPC_OBJFPC} ... {$endif}` in some of these cases would be more precise, but look even more complicated. If your project targets only one of these compilers, you can simplify your code, just pick the variant for your compiler and remove the `{$ifdef ...}`, `{$endif}` stuff.\n\n### Functions, procedures, primitive types\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/functions_primitives.dpr[]\n----\n\nTo return a value from a function, assign something to the magic `Result` variable. You can read and set the `Result` freely, just like a local variable.\n\n[source,pascal]\n----\nfunction MyFunction(const S: string): string;\nbegin\n  Result := S + 'something';\n  Result := Result + ' something more!';\n  Result := Result + ' and more!';\nend;\n----\n\nYou can also treat the function name (like `MyFunction` in example above) as the variable, to which you can assign. But I would discourage it in new code, as it looks \"fishy\" when used on the right side of the assignment expression. Just use `Result` always when you want to read or set the function result.\n\nIf you want to call the function itself recursively, you can of course do it. If you're calling a parameter-less function recursively, be sure to specify the parenthesis `()` (even though in Pascal you can usually omit the parentheses for a parameter-less function), this makes a recursive call to a parameter-less function different from accessing this function's current result. Like this:\n\n[source,pascal]\n----\nfunction SumIntegersUntilZero: Integer;\nvar\n  I: Integer;\nbegin\n  ReadLn(I);\n  Result := I;\n  if I <> 0 then\n    Result := Result + SumIntegersUntilZero();\nend;\n----\n\nYou can call `Exit` to end the execution of the procedure or function before it reaches the final `end;`. If you call parameter-less `Exit` in a function, it will return the last thing you set as `Result`. You can also use `Exit(X)` construct, to set the function result and exit *now* -- this is just like `return X` construct in C-like languages.\n\n[source,pascal]\n----\nfunction AddName(const ExistingNames, NewName: string): string;\nbegin\n  if ExistingNames = '' then\n    Exit(NewName);\n  Result := ExistingNames + ', ' + NewName;\nend;\n----\n\nNote that the function result can be discarded. Any function may be used just like a procedure. This makes sense if the function has some _side effect_ (e.g. it modifies a global variable) besides calculating the result. For example:\n\n[source,pascal]\n----\nvar\n  Count: Integer;\n  MyCount: Integer;\n\nfunction CountMe: Integer;\nbegin\n  Inc(Count);\n  Result := Count;\nend;\n\nbegin\n  Count := 10;\n  CountMe; // the function result is discarded, but the function is executed, Count is now 11\n  MyCount := CountMe; // use the result of the function, MyCount equals to Count which is now 12\nend.\n----\n\n### Testing (if)\n\nUse `if .. then` or `if .. then .. else` to run some code when some condition is satisfied. Unlike in the C-like languages, in Pascal you don't have to wrap the condition in parenthesis.\n\n[source,pascal]\n----\nvar\n  A: Integer;\n  B: boolean;\nbegin\n  if A > 0 then\n    DoSomething;\n\n  if A > 0 then\n  begin\n    DoSomething;\n    AndDoSomethingMore;\n  end;\n\n  if A > 10 then\n    DoSomething\n  else\n    DoSomethingElse;\n\n  // equivalent to above\n  B := A > 10;\n  if B then\n    DoSomething\n  else\n    DoSomethingElse;\nend;\n----\n\nThe `else` is paired with the last `if`. So this works as you expect:\n\n[source,pascal]\n----\nif A <> 0 then\n  if B <> 0 then\n    AIsNonzeroAndBToo\n  else\n    AIsNonzeroButBIsZero;\n----\n\nWhile the example with nested `if` above is correct, it is often better to place the nested `if` inside a `begin` ... `end` block in such cases. This makes the code more obvious to the reader, and it will remain obvious even if you mess up the indentation. The improved version of the example is below. When you add or remove some `else` clause in the code below, it's obvious to which condition it will apply (to the `A` test or the `B` test), so it's less error-prone.\n\n[source,pascal]\n----\nif A <> 0 then\nbegin\n  if B <> 0 then\n    AIsNonzeroAndBToo\n  else\n    AIsNonzeroButBIsZero;\nend;\n----\n\n### Logical, relational and bit-wise operators\n\nThe _logical operators_ are called `and`, `or`, `not`, `xor`. Their meaning is probably obvious (search for _\"exclusive or\"_ if you're unsure what _xor_ does:)). They take _boolean arguments_, and return a _boolean_. They can also act as _bit-wise operators_ when both arguments are integer values, in which case they return an integer.\n\nThe _relational (comparison)_ operators are `=`, `<>`, `>`, `<`, `\\<=`, `>=`. If you're accustomed to C-like languages, note that in Pascal you compare two values (check are they equal) using a single equality character `A = B` (unlike in C where you use `A == B`). The special _assignment_ operator in Pascal is `:=`.\n\nThe _logical (or bit-wise) operators have a higher precedence than relational operators_. You may need to use parenthesis around some expressions to have the desired order of the calculations.\n\nFor example this is a compilation error:\n\n[source,pascal]\n----\nvar\n  A, B: Integer;\nbegin\n  if A = 0 and B <> 0 then ... // INCORRECT example\n----\n\nThe above fails to compile, because the compiler first wants to perform a bit-wise `and` in the middle of the expression: `(0 and B)`. This is a bit-wise operation which returns an integer value. Then the compiler applies `=` operator which yields a boolean value `A = (0 and B)`. And finally the _\"type mismatch\"_ error is risen after trying to compare the boolean value `A = (0 and B)` and integer value `0`.\n\nThis is correct:\n\n[source,pascal]\n----\nvar\n  A, B: Integer;\nbegin\n  if (A = 0) and (B <> 0) then ...\n----\n\nThe _short-circuit evaluation_ is used. Consider this expression:\n\n[source,pascal]\n----\nif MyFunction(X) and MyOtherFunction(Y) then...\n----\n\n* It's guaranteed that `MyFunction(X)` will be evaluated first.\n* And if `MyFunction(X)` returns `false`, then the value of expression is known (the value of `false and whatever` is always `false`), and `MyOtherFunction(Y)` will not be executed at all.\n* Analogous rule is for `or` expression. There, if the expression is known to be `true` (because the 1st operand is `true`), the 2nd operand is not evaluated.\n* This is particularly useful when writing expressions like\n+\n[source,pascal]\n----\nif (A <> nil) and A.IsValid then...\n----\n+\nThis will work OK, even when `A` is `nil`. The keyword `nil` is a pointer equal to zero (when represented as a number). It is called a _null pointer_ in many other programming languages.\n\n// * Using `and` between two boolean values is a logical `and`, and the result is boolean. In other words, the result is `true` only if both operands are `true`, otherwise it's `false`.\n\n// * Using `and` between two integer values is a bit-wise `and`, and the result is integer. The operands are converted to have the same number of bits, and a similar rule is performed bit-by-bit, setting each bit to `0` or `1`. If you do this with potentially negative integer values, you should understand how negative numbers are encoded in memory (_\"two's complement\"_).\n\n### Testing single expression for multiple values (case)\n\nIf a different action should be executed depending on the value of some expression, then the `case .. of .. end` statement is useful.\n\n[source,pascal]\n----\ncase SomeValue of\n  0: DoSomething;\n  1: DoSomethingElse;\n  2: begin\n       IfItsTwoThenDoThis;\n       AndAlsoDoThis;\n     end;\n  3..10: DoSomethingInCaseItsInThisRange;\n  11, 21, 31: AndDoSomethingForTheseSpecialValues;\n  else DoSomethingInCaseOfUnexpectedValue;\nend;\n----\n\nThe `else` clause is optional (and corresponds to `default` in C-like languages). When no condition matches, and there's no `else`, then nothing happens.\n\nIn you come from C-like languages, and compare this with `switch` statement in these languages, you will notice that there is no automatic _fall-through_. This is a deliberate blessing in Pascal. You don't have to remember to place `break` instructions. In every execution, _at most one_ branch of the `case` is executed, that's it.\n\n### Enumerated and ordinal types and sets and constant-length arrays\n\nEnumerated type in Pascal is a very nice, opaque type. You will probably use it much more often than enums in other languages:)\n\n[source,pascal]\n----\ntype\n  TAnimalKind = (akDuck, akCat, akDog);\n----\n\nThe convention is to prefix the enum names with a two-letter shortcut of type name, hence `ak` = shortcut for _\"Animal Kind\"_. This is a useful convention, since the enum names are in the unit (global) namespace. So by prefixing them with `ak` prefix, you minimize the chances of collisions with other identifiers.\n\nNOTE: The collisions in names are not a show-stopper. It's Ok for different units to define the same identifier. But it's a good idea to try to avoid the collisions anyway, to keep code simple to understand and grep.\n\nNOTE: You can avoid placing enum names in the global namespace by compiler directive `{$scopedenums on}`. This means you will have to access them qualified by a type name, like `TAnimalKind.akDuck`. The need for `ak` prefix disappears in this situation, and you will probably just call the enums `Duck, Cat, Dog`. This is similar to C# enums.\n\nThe fact that enumerated type is _opaque_ means that it cannot be just assigned to and from an integer. However, for special use, you can use `Ord(MyAnimalKind)` to forcefully convert enum to int, or typecast `TAnimalKind(MyInteger)` to forcefully convert int to enum. In the latter case, make sure to check first whether `MyInteger` is in good range (0 to `Ord(High(TAnimalKind))`).\n\nEnumerated and ordinal types can be used as array indexes:\n\n[source,pascal]\n----\ntype\n  TArrayOfTenStrings = array [0..9] of string;\n  TArrayOfTenStrings1Based = array [1..10] of string;\n\n  TMyNumber = 0..9;\n  TAlsoArrayOfTenStrings = array [TMyNumber] of string;\n\n  TAnimalKind = (akDuck, akCat, akDog);\n  TAnimalNames = array [TAnimalKind] of string;\n----\n\nThey can also be used to create sets (a bit-fields internally):\n\n[source,pascal]\n----\ntype\n  TAnimalKind = (akDuck, akCat, akDog);\n  TAnimals = set of TAnimalKind;\nvar\n  A: TAnimals;\nbegin\n  A := [];\n  A := [akDuck, akCat];\n  A := A + [akDog];\n  A := A * [akCat, akDog];\n  Include(A, akDuck);\n  Exclude(A, akDuck);\nend;\n----\n\n### Loops (for, while, repeat, for .. in)\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/loops.dpr[]\n----\n\n*About the `repeat` and `while` loops*:\n\nThere are two differences between these loop types:\n\n1. The loop condition has an opposite meaning. In `while .. do` you tell it _when to continue_, but in `repeat .. until` you tell it _when to stop_.\n2. In case of `repeat`, _the condition is not checked at the beginning_. So the `repeat` loop always runs at least once.\n\n*About the `for I := ...` loops*:\n\nThe `for I := .. to .. do ...` construction it similar to the C-like `for` loop. However, it's more constrained, as you cannot specify arbitrary actions/tests to control the loop iteration. This is strictly for iterating over a consecutive numbers (or other ordinal types). The only flexibility you have is that you can use `downto` instead of `to`, to make numbers go downward.\n\nIn exchange, it looks clean, and is very optimized in execution. In particular, _the expressions for the lower and higher bound are only calculated once_, before the loop starts.\n\nNote that the value of the loop counter variable (`I` in this example) should be considered _undefined_ after the loop has finished, due to possible optimizations. Accessing the value of `I` after the loop may cause a compiler warning. _Unless_ you exit the loop prematurely by `Break` or `Exit`: in such case, the counter variable is guaranteed to retain the last value.\n\n*About the `for I in ...` loops*:\n\nThe `for I in .. do ..` is similar to `foreach` construct in many modern languages. It works intelligently on many built-in types:\n\n* It can iterate over all values in the array (example above).\n* It can iterate over all possible values of an enumerated type:\n+\n[source,pascal]\n----\nvar\n  AK: TAnimalKind;\nbegin\n  for AK in TAnimalKind do...\n----\n* It can iterate over all items included in the set:\n+\n[source,pascal]\n----\nvar\n  Animals: TAnimals;\n  AK: TAnimalKind;\nbegin\n  Animals := [akDog, akCat];\n  for AK in Animals do ...\n----\n* And it works on custom list types, generic or not, like `TObjectList` or `TFPGObjectList`.\n+\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/for_in_list.dpr[]\n----\n+\nWe didn't yet explain the concept of classes, so the last example may not be obvious to you yet -- just carry on, it will make sense later:)\n\n### Output, logging\n\nTo simply output strings in Pascal, use the `Write` or `WriteLn` routine. The latter automatically adds a newline at the end.\n\nThis is a \"magic\" routine in Pascal. It takes a variable number of arguments and they can have any type. They are all converted to strings when displaying, with a special syntax to specify padding and number precision.\n\n[source,pascal]\n----\nWriteLn('Hello world!');\nWriteLn('You can output an integer: ', 3 * 4);\nWriteLn('You can pad an integer: ', 666:10);\nWriteLn('You can output a float: ', Pi:1:4);\n----\n\nTo explicitly use newline in the string, use the `LineEnding` constant (from FPC RTL). (The _Castle Game Engine_ defines also a shorter `NL` constant.) Pascal strings do not interpret any special backslash sequences, so writing\n\n[source,pascal]\n----\nWriteLn('One line.\\nSecond line.'); // INCORRECT example\n----\n\ndoesn't work like some of you would think. This will work:\n\n[source,pascal]\n----\nWriteLn('One line.' + LineEnding + 'Second line.');\n----\n\nor just this:\n\n[source,pascal]\n----\nWriteLn('One line.');\nWriteLn('Second line.');\n----\n\nNote that this will only work in _console_ applications. Make sure you have `{$apptype CONSOLE}` (and *not* `{$apptype GUI}`) defined in your main program file. On some operating systems it actually doesn't matter and will work always (Unix), but on some operating systems trying to write something from a GUI application is an error (Windows).\n\n*In the Castle Game Engine:* use `WriteLnLog` or `WriteLnWarning`, never `WriteLn`, to print debug information. They will be always directed to some useful output. On Unix, standard output. On Windows GUI application, log file. On Android, the _Android logging facility_ (visible when you use `adb logcat`). The use of `WriteLn` should be limited to the cases when you write a command-line application (like a 3D model converter / generator) and you know that the _standard output_ is available.\n\n### Converting to a string\n\nTo convert an arbitrary number of arguments to a string (instead of just directly outputting them), you have a couple of options.\n\n* You can convert particular types to strings using specialized functions like `IntToStr` and `FloatToStr`. Furthermore, you can concatenate strings in Pascal simply by adding them. So you can create a string like this: `'My int number is ' + IntToStr(MyInt) + ', and the value of Pi is ' + FloatToStr(Pi)`.\n** _Advantage_: Absolutely flexible. There are many `XxxToStr` overloaded versions and friends (like `FormatFloat`), covering many types. Most of them are in the `SysUtils` unit.\n// They give you a lot of flexibility in formatting.\n** _Another advantage_: Consistent with the reverse functions. To convert a string (for example, user input) back to an integer or float, you use `StrToInt`, `StrToFloat` and friends (like `StrToIntDef`).\n** _Disadvantage_: A long concatenation of many `XxxToStr` calls and strings doesn't look nice.\n//For classes, they can override the `TObject.ToString` method.\n//It doesn't have that clean _separation of pattern and arguments_ property of `Format` call.\n\n* The `Format` function, used like `Format('%d %f %s', [MyInt, MyFloat, MyString])`. This is like `sprintf` function in the C-like languages. It inserts the arguments into the placeholders in the pattern. The placeholders may use special syntax to influence formatting, e.g. `%.4f` results in a floating-point format with 4 digits after the decimal point.\n** _Advantage_: The separation of _pattern_ string from _arguments_ looks clean. If you need to change the pattern string without touching the arguments (e.g. when translating), you can do it easily.\n** _Another advantage_: No compiler magic. You can use the same syntax to pass any number of arguments of an arbitrary type in your own routines (declare parameter as an `array of const`). You can then pass these arguments downward to `Format`, or deconstruct the list of parameters and do anything you like with them.\n** _Disadvantage_: Compiler does not check whether the pattern matches the arguments. Using a wrong placeholder type will result in an exception at runtime (`EConvertError` exception, not anything nasty like _Access Violation (Segmentation Fault)_ error).\n//Note that, unlike the C `sprintf`, the correctness at runtime can be completely verified (there are no dirty pointer tricks inside\n\n* `WriteStr(TargetString, ...)` routine behaves much like `Write(...)`, except that the result is saved to the `TargetString`.\n** _Advantage_: It supports all the features of `Write`, including the special syntax for formatting like `Pi:1:4`.\n** _Disadvantage_: The special syntax for formatting is a \"compiler magic\", implemented specifically for routines like this. This is sometimes troublesome, e.g. you cannot create your own routine `MyStringFormatter(...)` that would also allow the special syntax like `Pi:1:4`. For this reason (and also because it wasn't implemented for a long time in major Pascal compilers), this construction is not very popular.\n\n## Units\n\n### Overview\n\nUnits allow you to group common stuff (anything that can be declared), for usage by other units and programs. They are equivalent to _modules_ and _packages_ in other languages. They have an interface section, where you declare what is available for other units and programs, and then the implementation.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/myunit.pas[]\n----\n\nA program can use a unit by a `uses` keyword:\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/myunit_test.dpr[]\n----\n\n### Extensions used for units and programs\n\nSave the unit file `MyUnit` as `myunit.pas`. That is, lowercase with `.pas` extension.\n\n[NOTE]\n====\nOther conventions are possible.\n\nE.g. FPC allows other file extensions for units. And some people use `.pp` for unit files, like `myunit.pp`.\n\nUsing a different case is also possible. On Windows file systems, the letter case doesn't matter. But on Unix file systems is does matter and FPC allows only to use _the exact same case as was specified in Pascal `uses` clause_ (so `MyUnit.pas`) or _all lowercase_ (so `myunit.pas`). Since Pascal is case-insensitive, the first rule sometimes causes issues when people specify unit names with different case in different places.\n\nAll in all, we recommend the simple above rule _all lowercase, `.pas` extension_ for your projects. This matches the most common established practices and works with all compilers and file systems without issues.\n====\n\nSave the `program` to a file with:\n\n- `.dpr` extension (short for _\"Delphi Project\"_), if you want the project to be compatible with both _FPC/Lazarus_ and _Delphi_,\n\n- `.lpr` extension (short for _\"Lazarus Project\"_), if you want to use only _FPC/Lazarus_.\n\nNOTE: Other conventions are possible and used by some projects. E.g. some projects use `.pas` for main program file. Some projects use `.pp` for units or programs. There are reasonable reasons for this (e.g. for FPC programs, that don't use Lazarus LCL, neither description _\"Lazarus Project\"_ nor _\"Delphi Project\"_ are strictly correct)... But for the sake of simplicity, we recommend the above conventions (`.dpr` or `.lpr`), as they cover the most common established practices.\n\n### Initialization and finalization\n\nA unit may also contain `initialization` and `finalization` sections. This is the code executed when the program starts and ends.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/initialization_finalization.pas[]\n----\n\n### Units using each other\n\nOne unit can also use another unit. Another unit can be used in the interface section, or only in the implementation section. The former allows to define new public stuff (procedures, types...) on top of another unit's stuff. The latter is more limited (if you use a unit only in the implementation section, you can use its identifiers only in your implementation).\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/anotherunit.pas[]\n----\n\nIt is not allowed to have _circular unit dependencies in the interface_. That is, two units cannot use each other in the interface section.\n//that everything must be declared before it's used.\nThe reason is that in order to \"understand\"\n//(e.g. determine the memory layout of all the structures)\nthe interface section of a unit, the compiler must first \"understand\" all the units it uses in the interface section. Pascal language follows this rule strictly, and it allows a fast compilation and fully automatic detection on the compiler side _what units need to be recompiled_. There is no need to use complicated ``Makefile`` files for a simple task of compilation in Pascal, and there is no need to _recompile everything_ just to make sure that all dependencies are updated correctly.\n//, but also makes circular dependencies _between units interfaces_ impossible.\n//(That said, this constraint is not existing in some other languages. You can actually do parsing without \"complete understanding\" of your dependencies, just some stuff will have to be resolved later, e.g. at linking. You can also \"repeat\" the compilation until your knowledge is \"settled\". Anyway, you have to live with this constraint now, and enjoy fast compilation times.:)\n\nIt is _OK to make a circular dependency between units when at least one \"usage\" is only in the implementation_. So it's OK for unit `A` to use unit `B` in the interface, and then unit `B` to use unit `A` in the implementation.\n\n### Qualifying identifiers with unit name\n\nDifferent units may define the same identifier. To keep the code simple to read and search, you should usually avoid it, but it's not always possible.\n// in some situations (e.g. when you use a third-party library).\nIn such cases, the last unit on the `uses` clause \"wins\", which means that the identifiers it introduces hide the same identifiers introduced by earlier units.\n\nYou can always explicitly define a unit of a given identifier, by using it like `MyUnit.MyIdentifier`. This is the usual solution when the identifier you want to use from `MyUnit` is hidden by another unit. Of course you can also rearrange the order of units on your uses clause, although this can affect other declarations than the one you're trying to fix.\n\n[source,pascal]\n----\nprogram showcolor;\n\n{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}\n{$ifdef MSWINDOWS} {$apptype CONSOLE} {$endif}\n\n// Both Graphics and GoogleMapsEngine units define TColor type.\nuses Graphics, GoogleMapsEngine;\n\nvar\n  { This doesn't work like we want, as TColor ends up\n    being defined by GoogleMapsEngine. }\n  // Color: TColor;\n  { This works Ok. }\n  Color: Graphics.TColor;\nbegin\n  Color := clYellow;\n  WriteLn(Red(Color), ' ', Green(Color), ' ', Blue(Color));\nend.\n----\n\nIn case of units, remember that they have two `uses` clauses: one in the interface, and another one in the implementation. The rule _later units hide the stuff from earlier units_ is applied here consistently, which means that _units used in the implementation section_ can hide identifiers from units _used in the interface section_. However, remember that when reading the `interface` section, only the units used in the interface matter. This may create a confusing situation, where two seemingly-equal declarations are considered different by the compiler:\n\n[source,pascal]\n----\nunit UnitUsingColors;\n\n{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}\n\n// INCORRECT example\n\ninterface\n\nuses Graphics;\n\nprocedure ShowColor(const Color: TColor);\n\nimplementation\n\nuses GoogleMapsEngine;\n\nprocedure ShowColor(const Color: TColor);\nbegin\n  // WriteLn(ColorToString(Color));\nend;\n\nend.\n----\n\nThe unit `Graphics` (from Lazarus LCL) defines the `TColor` type. But the compiler will fail to compile the above unit, claiming that you don't implement a procedure `ShowColor` that matches the interface declaration. The problem is that unit `GoogleMapsEngine` also defines a `TColor` type. And it is used only in the `implementation` section, therefore it _shadows_ the `TColor` definition only in the implementation. The equivalent version of the above unit, where the error is obvious, looks like this:\n\n[source,pascal]\n----\nunit UnitUsingColors;\n\n{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}\n\n// INCORRECT example.\n// This is what the compiler \"sees\" when trying to compile previous example\n\ninterface\n\nuses Graphics;\n\nprocedure ShowColor(const Color: Graphics.TColor);\n\nimplementation\n\nuses GoogleMapsEngine;\n\nprocedure ShowColor(const Color: GoogleMapsEngine.TColor);\nbegin\n  // WriteLn(ColorToString(Color));\nend;\n\nend.\n----\n\nThe solution is trivial in this case, just change the implementation to explicitly use `TColor` from `Graphics` unit. You could fix it also by moving the `GoogleMapsEngine` usage, to the interface section and earlier than `Graphics`, although this could result in other consequences in real-world cases, when `UnitUsingColors` would define more things.\n\n[source,pascal]\n----\nunit UnitUsingColors;\n\n{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}\n\ninterface\n\nuses Graphics;\n\nprocedure ShowColor(const Color: TColor);\n\nimplementation\n\nuses GoogleMapsEngine;\n\nprocedure ShowColor(const Color: Graphics.TColor);\nbegin\n  // WriteLn(ColorToString(Color));\nend;\n\nend.\n----\n\n### Exposing one unit identifiers from another\n\nSometimes you want to take an identifier from one unit, and _expose_ it in a new unit. The end result should be that using the new unit will make the identifier available in the namespace.\n\nSometimes this is necessary to preserve backward compatibility with previous unit versions. Sometimes it's nice to \"hide\" an internal unit this way.\n\nThis can be done by redefining the identifier in your new unit.\n\n[source,pascal]\n----\nunit MyUnit;\n\n{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}\n\ninterface\n\nuses Graphics;\n\ntype\n  { Expose TColor from Graphics unit as TMyColor. }\n  TMyColor = TColor;\n\n  { Alternatively, expose it under the same name.\n    Qualify with unit name in this case, otherwise\n    we would refer to ourselves with \"TColor = TColor\" definition. }\n  TColor = Graphics.TColor;\n\nconst\n  { This works with constants too. }\n  clYellow = Graphics.clYellow;\n  clBlue = Graphics.clBlue;\n\nimplementation\n\nend.\n----\n\nNote that this trick cannot be done as easily with global procedures, functions and variables. With procedures and functions, you could expose a constant pointer to a procedure in another unit (see <<Callbacks>>), but that looks quite dirty.\n\nThe usual solution is to create trivial \"wrapper\" functions that simply call the functions from the internal unit, passing the parameters and return values as needed.\n\nTo make this work with global variables, one can use global (unit-level) properties, see <<Properties>>.\n\n## Classes\n\n### Basics\n\nWe have classes. At the basic level, a class is just a container for\n\n* _fields_ (which is fancy name for _\"a variable inside a class\"_),\n* _methods_ (which is fancy name for _\"a procedure or function inside a class\"_),\n* and _properties_ (which is a fancy syntax for something that looks like a field, but is in fact a pair of methods to _get_ and _set_ something; more in <<Properties>>).\n* Actually, there are more possibilities, described in <<More stuff inside classes and nested classes>>.\n\n[source,pascal]\n----\ntype\n  TMyClass = class\n    MyInt: Integer; // this is a field\n    property MyIntProperty: Integer read MyInt write MyInt; // this is a property\n    procedure MyMethod; // this is a method\n  end;\n\nprocedure TMyClass.MyMethod;\nbegin\n  WriteLn(MyInt + 10);\nend;\n----\n\n### Inheritance, virtual methods, override, reintroduce\n\nWe have inheritance and virtual methods.\n\nIn the example below, class `TMyClassDescendant` *inherits* from class `TMyClass`. The `TMyClassDescendant` is a *descendant* of `TMyClass`, and `TMyClass` is an *ancestor* of `TMyClassDescendant`.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/inheritance.dpr[]\n----\n\nWhen a method is *virtual* it means that the compiler searches for the method implementation at runtime, based on the actual class of the instance. What does this mean in practice?\n\n- Run the above example unmodified. Note that the method `MyVirtualMethod` is virtual. The call `C.MyVirtualMethod` selects the appropriate implementation based on the actual class of the instance `C`. When `C` is of class `TMyClassDescendant`, the `TMyClassDescendant.MyVirtualMethod` implementation is called. Thus the output should be:\n+\n```\nTMyClass shows MyInt + 10: 10\nTMyClassDescendant shows MyInt + 20: 20\n```\n\n- Now modify the above example removing the `virtual;` and `override;` pieces. Both calls `C.MyVirtualMethod` will now call the implementation from `TMyClass`, because `C` is declared as `TMyClass`, so at _compile-time_ all the compiler knows is that `C` is a `TMyClass`. The output will be:\n+\n```\nTMyClass shows MyInt + 10: 10\nTMyClass shows MyInt + 10: 20\n```\n+\nIn short, this is usually not what you want. You want virtual methods.\n\nBy default methods are not virtual, declare them with `virtual` to make them so. Overrides must be marked with `override`, otherwise you will get a warning. To hide a method (declared in ancestor as `virtual`) without overriding it (usually you don't want to do this, unless you know what you're doing) use `reintroduce`.\n\n### Classes and class instances, constructors, destructors\n\nExample in the section above shows a *class* called `TMyClass` (and another class called `TMyClassDescendant`). The *class* is a _type_, you can also think of it as a _template_. The class itself doesn't hold any values -- there is no memory reserved for the field `MyInt: Integer` declared in the example above.\n\nNOTE: It is actually possible for a class to _\"hold values\"_ by using _class variables_, but for now let's forget about this possibility. Focus on simple classes that have only regular fields.\n\nTo reserve memory for the fields, we need to create a *class instance*.\n\nCreating the class instance is done by invoking a *constructor*.\n\n- Constructor is a special kind of a method, using the keyword `constructor`.\n\n- Before invoking a constructor, a memory for the class instance is allocated, and then the constructor code is called.\n\n- You don't need to define a constructor in all your classes. All classes implicitly descend from the `TObject` which has a parameter-less constructor called `Create`. So you always have a constructor, even if you didn't define one.\n\n- But you *can* define a constructor in your class. It's the best way to initialize a class instance. If you want to later depend that e.g. \"initial value of field X is Y\", then make it so (`X := Y;`) in the constructor.\n\n- Your own constructors are usually also called just `Create`. More details about naming constructors and destructors are in <<The virtual destructor called Destroy>>.\n\nYou invoke the constructor, allocating a class instance, like this:\n\n[source,pascal]\n----\nX := TMyClass.Create;\n----\n\nYou define your own constructor like this:\n\n[source,pascal]\n----\ntype\n  TMyClass = class\n  public\n    X: Integer;\n    constructor Create;\n  end;\n\nconstructor TMyClass.Create;\nbegin\n  inherited Create; // Call the ancestor constructor\n  // Initialization code here\n  X := 123;\nend;\n----\n\nConversely, when a class is _destroyed_, a `destructor` is called.\n\n- It is again a special kind of a method, using the keyword `destructor`.\n\n- After invoking the destructor, a memory for the class instance is released. Accessing the fields of the destroyed instance is no longer allowed.\n\n- Again, you don't need to define a destructor in all your classes. All classes implicitly descend from the `TObject` which has a parameter-less destructor called `Destroy`.\n\n- But you *can* define a destructor in your class. This is your last chance to do any \"cleanup\". E.g. maybe your class instance created some other class instances, internal, and now they need to be freed.\n\n- If you define one, there should be only one destructor, called `Destroy`, always with `override;`. More details why it should be so are in <<The virtual destructor called Destroy>>.\n\nHere's an example:\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/constructor_destructor.dpr[]\n----\n\n### Testing class (is), typecasting (as, TMyClass(X))\n\nTo test the class of an instance at runtime, use the `is` operator. To typecast the instance to a specific class, use the `as` operator.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/is_as.dpr[]\n----\n\nInstead of casting using `X as TMyClass`, you can also use the _unchecked_ typecast `TMyClass(X)`. This is faster, but results in an undefined behavior if the `X` is not, in fact, a `TMyClass` descendant. So don't use the `TMyClass(X)` typecast, or use it only in a code where it's blindingly obvious that it's correct, for example right after testing with `is`:\n\n[source,pascal]\n----\nif A is TMyClass then\n  (A as TMyClass).CallSomeMethodOfMyClass;\n// below is marginally faster\nif A is TMyClass then\n  TMyClass(A).CallSomeMethodOfMyClass;\n----\n\n### Properties\n\nProperties are a very nice _\"syntactic sugar\"_ to\n\n1. Make something that looks like a field (can be read and set) but underneath is realized by calling a _getter_ and _setter_ methods. The typical usage is to perform some side-effect (e.g. redraw the screen) each time some value changes.\n2. Make something that looks like a field, but is read-only. In effect, it's like a constant or a parameter-less function.\n\n[source,pascal]\n----\ntype\n  TWebPage = class\n  private\n    FURL: string;\n    FColor: TColor;\n    function SetColor(const Value: TColor);\n  public\n    { No way to set it directly.\n      Call the Load method, like Load('http://www.freepascal.org/'),\n      to load a page and set this property. }\n    property URL: string read FURL;\n    procedure Load(const AnURL: string);\n    property Color: TColor read FColor write SetColor;\n  end;\n\nprocedure TWebPage.Load(const AnURL: string);\nbegin\n  FURL := AnURL;\n  NetworkingComponent.LoadWebPage(AnURL);\nend;\n\nfunction TWebPage.SetColor(const Value: TColor);\nbegin\n  if FColor <> Value then\n  begin\n    FColor := Value;\n    // for example, cause some update each time value changes\n    Repaint;\n    // as another example, make sure that some underlying instance,\n    // like a \"RenderingComponent\" (whatever that is),\n    // has a synchronized value of Color.\n    RenderingComponent.Color := Value;\n  end;\nend;\n----\n\n// { compare with the old value, to shield from making\n//   useless assignments to RenderingComponent.Color.\n//   This is a common approach to guarantee that setting WebPage.Color\n//   many times to the same value will be fast,\n//   even if setting RenderingComponent.Color many times to the same value\n//   would be slow. }\n\nNote that instead of specifying a method, you can also specify a field (typically a private field) to directly get or set. In the example above, the `Color` property uses a _setter_ method `SetColor`. But for getting the value, the `Color` property refers directly to the private field `FColor`. Directly referring to a field is faster than implementing trivial getter or setter methods (faster for you, and faster at execution).\n\nWhen declaring a property you specify:\n\n. Whether it can be read, and how (by directly reading a field, or by using a \"getter\" method).\n. And, in a similar manner, whether it can be set, and how (by directly writing to a designated field, or by calling a \"setter\" method).\n\nThe compiler checks that the types and parameters of indicated fields and methods match with the property type. For example, to read an `Integer` property you have to either provide an `Integer` field, or a parameter-less method that returns an `Integer`.\n\n\nTechnically, for the compiler, the \"getter\" and \"setter\" methods are just normal methods and they can do absolutely anything (including side-effects or randomization). But it's a good convention to design properties to behave more-or-less like fields:\n\n// There are some good conventions to follow when creating properties. These are only conventions, the compiler doesn't prevent you from making something weird using properties -- f. But the good\n// They should be somewhat predictable, like fields:\n\n* The _getter_ function should have no visible side-effects (e.g. it should not read some input from file / keyboard). It should be deterministic (no randomization, not even pseudo-randomization :). Reading a property many times should be valid, and return the same value, if nothing changed in-between.\n+\nNote that it's OK for _getter_ to have some _invisible_ side-effect, for example to cache a value of some calculation (known to produce the same results for given instance), to return it faster next time. This is in fact one of the cool possibilities of a \"getter\" function.\n\n* The _setter_ function should always set the requested value, such that calling the _getter_ yields it back. Do not reject invalid values silently in the \"setter\" (raise an exception if you must). Do not convert or scale the requested value. The idea is that after `MyClass.MyProperty := 123;` the programmer can expect that `MyClass.MyProperty = 123`.\n\n* The _read-only properties_ are often used to make some field read-only from the outside. Again, the good convention is to make it behave like a constant, at least constant for this object instance with this state. The value of the property should not change unexpectedly. _Make it a function, not a property, if using it has a side effect or returns something random._\n\n* The _\"backing\" field of a property is almost always private_, since the idea of a property is to encapsulate all outside access to it.\n\n* It's technically possible to make _set-only properties_, but I have not yet seen a good example of such thing:)\n\nNOTE: Properties can also be defined outside of class, at a unit level. They serve an analogous purpose then: look like a global variable, but are backed by a _getter_ and _setter_ routines.\n\n#### Serialization of properties\n\n_Published properties_ are the basis of a _serialization_ (also known as _streaming components_) in Pascal. _Serialization_ means that the instance data is recorded into a stream (like a file), from which it can be later restored.\n\nSerialization is what happens when Lazarus reads (or writes) the component state from an `xxx.lfm` file. (In Delphi, the equivalent file has `.dfm` extension.) You can also use this mechanism explicitly, using routines like `ReadComponentFromTextStream` from the `LResources` unit. You can also use other serialization algorithms, e.g. `FpJsonRtti` unit (serializing to JSON).\n\n*In the Castle Game Engine:* Use the `CastleComponentSerialize` unit (based on `FpJsonRtti`) to serialize our user-interface and transformation component hierarchies.\n\nAt each property, you can declare some additional things that will be helpful for any serialization algorithm:\n\n* You can specify the property default value (using the `default` keyword). Note that you are still required to initialize the property in the constructor to this exact default value (it is not done automatically). The `default` declaration is merely an information to the serialization algorithm: _\"when the constructor finishes, the given property has the given value\"_.\n\n* Whether the property should be stored at all (using the `stored` keyword).\n\n### Exceptions - Quick Example\n\nWe have exceptions. They can be caught with `try ... except ... end` clauses, and we have `finally` sections like `try ... finally ... end`.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/exception_finally.dpr[]\n----\n\nNote that the `finally` clause is executed even if you exit the block using the `Exit` (from function / procedure / method) or `Break` or `Continue` (from loop body).\n\nSee the <<Exceptions>> chapter for more in-depth description of _exceptions_.\n\n### Visibility specifiers\n\nAs in most object-oriented languages, we have visibility specifiers to hide fields / methods / properties.\n\nThe basic visibility levels are:\n\n`public`:: everyone can access it, including the code in other units.\n`private`:: only accessible in this class.\n`protected`:: only accessible in this class and descendants.\n\nThe explanation of `private` and `protected` visibility above is not precisely true. The code _in the same unit_ can overcome their limits, and access the `private` and `protected` stuff freely. Sometimes this is a nice feature, allows you to implement tightly-connected classes. Use `strict private` or `strict protected` to secure your classes more tightly. See the <<Private and strict private>>.\n\nBy default, if you don't specify the visibility, then the visibility of declared stuff is `public`. The exception is for classes compiled with `{$M+}`, or descendants of classes compiled with `{$M+}`, which includes all descendants of `TPersistent`, which also includes all descendants of `TComponent` (since `TComponent` descends from `TPersistent`). For them, the default visibility specifier is `published`, which is like `public`, but in addition the streaming system knows to handle this.\n\nNot every field and property type is allowed in the `published` section (not every type can be streamed, and only classes can be streamed from simple fields). Just use `public` if you don't care about streaming but want something available to all users.\n\n### Default ancestor\n\nIf you don't declare the ancestor type, every `class` inherits from `TObject`.\n\n### Self\n\nThe special keyword `Self` can be used within the class implementation to explicitly refer to your own instance. It is equivalent to `this` from C++, Java and similar languages.\n\n### Calling inherited method\n\nWithin a method implementation, if you call another method, then by default you call the method of your own class. In the example code below, `TMyClass2.MyOtherMethod` calls `MyMethod`, which ends up calling `TMyClass2.MyMethod`.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/method_calls_inheritance_1.dpr[]\n----\n\nIf the method is not defined in a given class, then it calls the method of an ancestor class. In effect, when you call `MyMethod` on an instance of `TMyClass2`, then\n\n* The compiler looks for `TMyClass2.MyMethod`.\n* If not found, it looks for `TMyClass1.MyMethod`.\n* If not found, it looks for `TObject.MyMethod`.\n* if not found, then the compilation fails.\n\nYou can test it by commenting out the `TMyClass2.MyMethod` definition in the example above. In effect, `TMyClass1.MyMethod` will be called by `TMyClass2.MyOtherMethod`.\n\nSometimes, you don't want to call the method of your own class. You want to call the method of an ancestor (or ancestor's ancestor, and so on). To do this, add the keyword `inherited` before the call to `MyMethod`, like this:\n\n[source,pascal]\n----\ninherited MyMethod;\n----\n\nThis way you _force_ the compiler to start searching from an ancestor class. In our example, it means that compiler is searching for `MyMethod` inside `TMyClass1.MyMethod`, then `TObject.MyMethod`, and then gives up. It does not even consider using the implementation of `TMyClass2.MyMethod`.\n\nTIP: Go ahead, change the implementation of `TMyClass2.MyOtherMethod` above to use `inherited MyMethod`, and see the difference in the output.\n\nThe `inherited` call is often used to call the ancestor method of the same name. This way the descendants can enhance the ancestors (keeping the ancestor functionality, instead of replacing the ancestor functionality). Like in the example below.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/method_calls_inherited.dpr[]\n----\n\nSince using `inherited` to call a method with the same name, with the same arguments, is a very common case, there is a special shortcut for it: you can just write `inherited;` (`inherited` keyword followed immediately by a semicolon, instead of a method name). This means \"_call an inherited method with the same name, passing it the same arguments as the current method_\".\n\nTIP: In the above example, all the `inherited ...;` calls could be replaced by a simple `inherited;`.\n\nNote 1: The `inherited;` is really just a shortcut for calling the ancestor's method with the _same variables passed in_. If you have modified your own parameter (which is possible, if the parameter is not `const`), then the ancestor's method can receive different input values from your descendant. Consider this:\n\n[source,pascal]\n----\nprocedure TMyClass2.MyMethod(A: Integer);\nbegin\n  WriteLn('TMyClass2.MyMethod beginning ', A);\n  A := 456;\n  { This calls TMyClass1.MyMethod with A = 456,\n    regardless of the A value passed to this method (TMyClass2.MyMethod). }\n  inherited;\n  WriteLn('TMyClass2.MyMethod ending ', A);\nend;\n----\n\nNote 2: You usually want to make the `MyMethod` _virtual_ when many classes (along the \"_inheritance chain_\") define it. More about the virtual methods in the section below. But the `inherited` keyword works regardless of whether the method is virtual or not. The `inherited` always means that the compiler starts searching for the method in an ancestor, and it makes sense for both _virtual_ and _non-virtual_ methods.\n\n\n### Virtual methods, override and reintroduce\n\nBy default, the methods are _not virtual_. This is similar to C++, and unlike Java.\n\nWhen a method is _not virtual_, the compiler determines which method to call based on the currently _declared_ class type, not based on the _actually created_ class type. The difference seems subtle, but it's important when your variable is declared to have a class like `TFruit`, but it may be in fact a descendant class like `TApple`.\n\nThe idea of the object-oriented programming is that _the descendant class is always as good as the ancestor_, so the compiler allows to use a descendant class always when the ancestor is expected. When your method is not virtual, this can have undesired consequences. Consider the example below:\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/without_virtual_methods.dpr[]\n----\n\nThis example will print\n\n----\nWe have a fruit with class TApple\nWe eat it:\nEating a fruit\n----\n\nIn effect, the call `Fruit.Eat` called the `TFruit.Eat` implementation, and nothing calls the `TApple.Eat` implementation.\n\nIf you think about how the compiler works, this is natural: when you wrote the `Fruit.Eat`, the `Fruit` variable was declared to hold a class `TFruit`. So the compiler was searching for the method called `Eat` within the `TFruit` class. If the `TFruit` class would not contain such method, the compiler would search within an ancestor (`TObject` in this case). But the compiler _cannot search within descendants (like `TApple`)_, as it doesn't know whether the _actual class_ of `Fruit` is `TApple`, `TFruit`, or some other `TFruit` descendant (like a `TOrange`, not shown in the example above).\n\nIn other words, the _method to be called_ is determined _at compile-time_.\n\nUsing the _virtual methods_ changes this behavior. *If the `Eat` method would be virtual* (an example of it is shown below), then the actual implementation to be called is determined _at runtime_. If the `Fruit` variable will hold an instance of the class `TApple` (even if it's declared as `TFruit`), then the `Eat` method will be searched within the `TApple` class first.\n\nIn Object Pascal, to define a method as _virtual_, you need to\n\n* Mark its first definition (in the top-most ancestor) with the `virtual` keyword.\n* Mark all the other definitions (in the descendants) with the `override` keyword. All the overridden versions must have exactly the same parameters (and return the same types, in case of functions).\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/with_virtual_methods.dpr[]\n----\n\nThis example will print\n\n----\nWe have a fruit with class TApple\nWe eat it:\nEating an apple\n----\n\nInternally, virtual methods work by having so-called _virtual method table_ associated with each class. This table is a list of pointers to the implementations of virtual methods for this class. When calling the `Eat` method, the compiler looks into a virtual method table associated with the actual class of `Fruit`, and uses a pointer to the `Eat` implementation stored there.\n\nIf you don't use the `override` keyword, the compiler will warn you that you're _hiding_ (obscuring) the virtual method of an ancestor with a non-virtual definition. If you're sure that this is what you want, you can add a `reintroduce` keyword. But in most cases, you will rather want to keep the method virtual, and add the `override` keyword, thus making sure that it's always invoked correctly.\n\n## Freeing classes\n\n### Remember to free the class instances\n\nThe class instances have to be manually freed, otherwise you get memory leaks.\n\nWe advise to automatically detect memory leaks using:\n\n- FPC command-line options `-gl -gh`\n- Delphi `ReportMemoryLeaksOnShutdown := true`\n- Castle Game Engine `detect_memory_leaks=\"true\"` in `CastleEngineManifest.xml`\n\nSee https://castle-engine.io/memory_leaks for more information.\n\nNOTE: You don't need to free the instances of raised exceptions. Although you do create an instance when raising an exception (and it's a perfectly normal class instance). But this class instance is freed automatically.\n\n### How to free\n\nTo free the class instance, it's best to call `FreeAndNil(A)` from `SysUtils` unit on your class instance. It checks whether `A` is `nil`, if not -- calls its destructor, and sets `A` to `nil`. So calling it many times in a row is not an error.\n\nIt is more-or-less a shortcut for\n\n[source,pascal]\n----\nif A <> nil then\nbegin\n  A.Destroy;\n  A := nil;\nend;\n----\n\nActually, that's an oversimplification, as `FreeAndNil` does a useful trick and sets the variable `A` to `nil` *before* calling the destructor on a suitable reference. This helps to prevent a certain class of bugs -- the idea is that the \"outside\" code should never access a half-destructed instance of the class.\n\nOften you will also see people using the `A.Free` method, which is like doing\n\n[source,pascal]\n----\nif A <> nil then\n  A.Destroy;\n----\n\nThis frees the `A`, unless it's `nil`.\n\nNote that in normal circumstances, you should never call a method on an instance which may be `nil`. So the call `A.Free` may look suspicious at the first sight, if `A` can be `nil`. However, the `Free` method is an exception to this rule. It does something dirty in the implementation -- namely, checks whether `Self <> nil`.\n\n[NOTE]\n====\nThis trick (officially allowing the method to be used with `Self` equal `nil`) is possible only in non-virtual methods.\n\nIn the implementation of such method, as long as `Self = nil` is possible, the method cannot call any virtual methods or access any fields, as these would cause _Access Violation (Segmentation Fault)_ error when called on a `nil` instance. See the sample code https://github.com/modern-pascal/modern-pascal-introduction/blob/master/code-samples/method_with_self_nil.dpr[method_with_self_nil.dpr].\n\nWe discourage from using this trick in your own code (for virtual or non-virtual methods) as it is counter-intuitive to normal usage. In general all instance methods should be able to assume that they work on valid (non-nil) instance and can access fields and call any other methods (virtual or not).\n====\n\nWe advise using `FreeAndNil(A)` always, without exceptions, and never to call directly the `Free` method or `Destroy` destructor.\n\nThe _Castle Game Engine_ does it like that. It helps to keep a nice assertion that _all references are either nil, or point to valid instances_. Though note that using `FreeAndNil(A)`  doesn't *guarantee* this assertion, it only helps with this. For example, if you copy the instance reference, and call `FreeAndNil(A)` on one copy, the other copy will be a non-nil dangling pointer.\n\n[source,pascal]\n----\nA := TMyClass.Create;\nB := A;\nFreeAndNil(A);\n// B now contains a dangling pointer\n----\n\nMore about dealing with this in the later section about _\"Free notification\"_.\n\nStill, `FreeAndNil(A)` takes care of the most trivial cases, so it's a good habit to use it IMHO. You will appreciate it when debugging some errors, it is nice to easily observe _\"``X`` is already freed, because `X` is `nil` now\"_.\n\n### Manual and automatic freeing\n\nIn many situations, the need to free the instance is not much problem. You just write a destructor, that matches a constructor, and deallocates everything that was allocated in the constructor (or, more completely, in the whole lifetime of the class). Be careful to only free each thing *once*. Usually it's a good idea to set the freed reference to `nil`, usually it's most comfortable to do it by calling the `FreeAndNil(A)`.\n\nSo, like this:\n\n[source,pascal]\n----\nuses SysUtils;\n\ntype\n  TGun = class\n  end;\n\n  TPlayer = class\n    Gun1, Gun2: TGun;\n    constructor Create;\n    destructor Destroy; override;\n  end;\n\nconstructor TPlayer.Create;\nbegin\n  inherited;\n  Gun1 := TGun.Create;\n  Gun2 := TGun.Create;\nend;\n\ndestructor TPlayer.Destroy;\nbegin\n  FreeAndNil(Gun1);\n  FreeAndNil(Gun2);\n  inherited;\nend;\n----\n\nTo avoid the need to explicitly free the instance, one can also use the `TComponent` feature of _\"ownership\"_. An object that is _owned_ will be automatically freed by the _owner_. The mechanism is smart and it will never free an already freed instance (so things will also work correctly if you manually free the owned object earlier). We can change the previous example to this:\n\n[source,pascal]\n----\nuses SysUtils, Classes;\n\ntype\n  TGun = class(TComponent)\n  end;\n\n  TPlayer = class(TComponent)\n    Gun1, Gun2: TGun;\n    constructor Create(AOwner: TComponent); override;\n  end;\n\nconstructor TPlayer.Create(AOwner: TComponent);\nbegin\n  inherited;\n  Gun1 := TGun.Create(Self);\n  Gun2 := TGun.Create(Self);\nend;\n----\n\nNote that we need to override a virtual `TComponent` constructor here. So we cannot change the constructor parameters. (Actually, you can -- declare a new constructor with `reintroduce`. But be careful, as some functionality, e.g. streaming, will still use the virtual constructor, so make sure it works right in either case.)\n\nNote that you can always use `nil` value for the owner. This way the _\"ownership\"_ mechanism will not be used for this component. It makes sense if you need to use the `TComponent` descendant, but you want to always manually free it. To do this, you would create a component descendant like this: `ManualGun := TGun.Create(nil);`.\n\nAnother mechanism for automatic freeing is the `OwnsObjects` functionality (by default already `true`!) of list-classes like `TFPGObjectList` or `TObjectList`. So we can also write:\n\n[source,pascal]\n----\nuses SysUtils, Classes, FGL;\n\ntype\n  TGun = class\n  end;\n\n  TGunList = {$ifdef FPC}specialize{$endif} TFPGObjectList<TGun>;\n\n  TPlayer = class\n    Guns: TGunList;\n    Gun1, Gun2: TGun;\n    constructor Create;\n    destructor Destroy; override;\n  end;\n\nconstructor TPlayer.Create;\nbegin\n  inherited;\n  // Actually, the parameter true (OwnsObjects) is already the default\n  Guns := TGunList.Create(true);\n  Gun1 := TGun.Create;\n  Guns.Add(Gun1);\n  Gun2 := TGun.Create;\n  Guns.Add(Gun2);\nend;\n\ndestructor TPlayer.Destroy;\nbegin\n  { We have to take care to free the list.\n    It will automatically free its contents. }\n  FreeAndNil(Guns);\n\n  { No need to free the Gun1, Gun2 anymore. It's a nice habit to set to \"nil\"\n    their references now, as we know they are freed. In this simple class,\n    with so simple destructor, it's obvious that they cannot be accessed\n    anymore -- but doing this pays off in case of larger and more complicated\n    destructors.\n\n    Alternatively, we could avoid declaring Gun1 and Gun2,\n    and instead use Guns[0] and Guns[1] in own code.\n    Or create a method like Gun1 that returns Guns[0]. }\n  Gun1 := nil;\n  Gun2 := nil;\n  inherited;\nend;\n----\n\nBeware that the list classes \"ownership\" mechanism is simple, and you will get an error if you free the instance using some other means, while it's also contained within a list. Use the `Extract` method to remove something from a list without freeing it, thus taking the responsibility to free it yourself.\n\n*In the Castle Game Engine*: The descendants of `TX3DNode` have automatic memory management when inserted as children of another `TX3DNode`. The root X3D node, `TX3DRootNode`, is in turn usually owned by `TCastleSceneCore`. Some other things also have a simple ownership mechanism -- look for parameters and properties called `OwnsXxx`.\n\n### The virtual destructor called Destroy\n\nAs you saw in the examples above, when the class is destroyed, its `destructor` called `Destroy` is called.\n\nIn theory, you could have multiple destructors, but in practice it's almost never a good idea. It's much easier to have only one destructor called `Destroy`, which is in turn called by the `Free` method, which is in turn called by the `FreeAndNil` procedure.\n\nThe `Destroy` destructor in the `TObject` is defined as a _virtual_ method, so you should always mark it with the `override` keyword in all your classes (since all classes descend from `TObject`). This makes the `Free` method work correctly. Recall how the virtual methods work from the <<virtual-methods-section>>.\n\n[NOTE]\n====\nThis information about _destructors_ is, indeed, inconsistent with the _constructors_.\n\nIt's normal that a class has multiple constructors. Usually they are all called `Create`, and only have different parameters, but it's also OK to invent other names for constructors.\n\nAlso, the `Create` constructor in the `TObject` is _not virtual_, so you do not mark it with `override` in the descendants.\n\nThis all gives you a bit of extra flexibility when defining constructors. It is often not necessary to make them virtual, so by default you're not forced to do it.\n\nNote, however, that this changes for `TComponent` descendants. The `TComponent` defines a virtual constructor `Create(AOwner: TComponent)`. It needs a virtual constructor in order for the streaming system to work. When defining descendants of the `TComponent`, you should override this constructor (and mark it with the `override` keyword), and perform all your initialization inside it. It is still OK to define additional constructors, but they should only act as _\"helpers\"_. The instance should always work when created using the `Create(AOwner: TComponent)` constructor, otherwise it will not be correctly constructed when streaming. The _streaming_ is used e.g. when saving and loading this component on a Lazarus form.\n====\n\n### Free notification\n\nIf you copy a reference to the instance, such that you have two references to the same memory, and then one of them is freed -- the other one becomes a _\"dangling pointer\"_. It should not be accessed, as it points to a memory that is no longer allocated. Accessing it may result in a runtime error, or garbage being returned (as the memory may be reused for other stuff in your program).\n\nUsing the `FreeAndNil` to free the instance doesn't help here. `FreeAndNil` sets to `nil` only the reference it got -- there's no way for it to set all other references automatically. Consider this code:\n\n[source,pascal]\n----\nvar\n  Obj1, Obj2: TObject;\nbegin\n  Obj1 := TObject.Create;\n  Obj2 := Obj1;\n  FreeAndNil(Obj1);\n\n  // what happens if we access Obj1 or Obj2 here?\nend;\n----\n\n1. At the end of this block, the `Obj1` is `nil`. If some code has to access it, it can reliably use `if Obj1 <> nil then ...` to avoid calling methods on a freed instance, like\n+\n[source,pascal]\n----\nif Obj1 <> nil then\n  WriteLn(Obj1.ClassName);\n----\n+\nTrying to access a field of a `nil` instance results in a predictable exception at runtime. So even if some code will not check `Obj1 <> nil`, and will blindly access `Obj1` field, you will get a clear exception at runtime.\n+\nSame goes for calling a virtual method, or calling a non-virtual method that accessed a field of a `nil` instance.\n\n2. With `Obj2`, things are less predictable. It's not `nil`, but it's invalid. Trying to access a field of a non-nil invalid instance\n//(or call a method that accessed a field of such instance)\nresults in an unpredictable behavior -- maybe an access violation exception, maybe a garbage data returned.\n\nThere are various solutions to it:\n\n* One solution is to, well, be careful and read the documentation. Don't assume anything about the lifetime of the reference, if it's created by other code. If a class `TCar` has a field pointing to some instance of `TWheel`, it's a _convention_ that the reference to _wheel_ is valid as long as the reference to _car_ exists, and the _car_ will free its _wheels_ inside its destructor. But that's just a convention, the documentation should mention if there's something more complicated going on.\n\n* In the above example, right after freeing the `Obj1` instance, you can simply set the `Obj2` variable explicitly to `nil`. That's trivial in this simple case.\n\n* The most future-proof solution is to use `TComponent` class \"free notification\" mechanism. One component can be notified when another component is freed, and thus set its reference to `nil`.\n+\nThus you get something like a _weak reference_. It can cope with various usage scenarios, for example you can allow the code from outside of the class to set your reference, and the outside code can also free the instance at any time.\n+\nThis requires both classes to descend from `TComponent`. Using it in general boils down to calling `FreeNotification` , `RemoveFreeNotification`, and overriding `Notification`.\n+\nHere's a complete example, showing how to use this mechanism, together with constructor / destructor and a setter property. Sometimes it can be done simpler, but this is the full-blown version that is always correct:)\n+\n[source,pascal]\n----\ntype\n  TControl = class(TComponent)\n  end;\n\n  TContainer = class(TComponent)\n  private\n    FSomeSpecialControl: TControl;\n    procedure SetSomeSpecialControl(const Value: TControl);\n  protected\n    procedure Notification(AComponent: TComponent; Operation: TOperation); override;\n  public\n    destructor Destroy; override;\n    property SomeSpecialControl: TControl\n      read FSomeSpecialControl write SetSomeSpecialControl;\n  end;\n\nimplementation\n\nprocedure TContainer.Notification(AComponent: TComponent; Operation: TOperation);\nbegin\n  inherited;\n  if (Operation = opRemove) and (AComponent = FSomeSpecialControl) then\n    { set to nil by SetSomeSpecialControl to clean nicely }\n    SomeSpecialControl := nil;\nend;\n\nprocedure TContainer.SetSomeSpecialControl(const Value: TControl);\nbegin\n  if FSomeSpecialControl <> Value then\n  begin\n    if FSomeSpecialControl <> nil then\n      FSomeSpecialControl.RemoveFreeNotification(Self);\n    FSomeSpecialControl := Value;\n    if FSomeSpecialControl <> nil then\n      FSomeSpecialControl.FreeNotification(Self);\n  end;\nend;\n\ndestructor TContainer.Destroy;\nbegin\n  { set to nil by SetSomeSpecialControl, to detach free notification }\n  SomeSpecialControl := nil;\n  inherited;\nend;\n----\n\n### Free notification observer (Castle Game Engine)\n\n*In Castle Game Engine* we encourage to use `TFreeNotificationObserver` from `CastleClassUtils` unit instead of directly calling `FreeNotification`, `RemoveFreeNotification` and overriding `Notification`.\n\nIn general using `TFreeNotificationObserver` looks a bit simpler than using `FreeNotification` mechanism directly (though I admit it is a matter of taste). But in particular when _the same class instance must be observed because of multiple reasons_ then `TFreeNotificationObserver` is much simpler to use (directly using `FreeNotification` in this case can get complicated, as you have to watch to not unregister the notification too soon).\n\nThis is the example code using `TFreeNotificationObserver`, to achieve the same effect as example in the previous section:\n\n[source,pascal]\n----\ntype\n  TControl = class(TComponent)\n  end;\n\n  TContainer = class(TComponent)\n  private\n    FSomeSpecialControlObserver: TFreeNotificationObserver;\n    FSomeSpecialControl: TControl;\n    procedure SetSomeSpecialControl(const Value: TControl);\n    procedure SomeSpecialControlFreeNotification(const Sender: TFreeNotificationObserver);\n  public\n    constructor Create(AOwner: TComponent); override;\n    property SomeSpecialControl: TControl\n      read FSomeSpecialControl write SetSomeSpecialControl;\n  end;\n\nimplementation\n\nuses CastleComponentSerialize;\n\nconstructor TContainer.Create(AOwner: TComponent);\nbegin\n  inherited;\n  FSomeSpecialControlObserver := TFreeNotificationObserver.Create(Self);\n  FSomeSpecialControlObserver.OnFreeNotification := {$ifdef FPC}@{$endif} SomeSpecialControlFreeNotification;\nend;\n\nprocedure TContainer.SetSomeSpecialControl(const Value: TControl);\nbegin\n  if FSomeSpecialControl <> Value then\n  begin\n    FSomeSpecialControl := Value;\n    FSomeSpecialControlObserver.Observed := Value;\n  end;\nend;\n\nprocedure TContainer.SomeSpecialControlFreeNotification(const Sender: TFreeNotificationObserver);\nbegin\n  // set property to nil when the referenced component is freed\n  SomeSpecialControl := nil;\nend;\n----\n\nSee https://castle-engine.io/custom_components .\n\n## Exceptions\n\n### Overview\n\nExceptions allow to _interrupt the normal execution of the code_.\n\n- At any point within the program, you can *raise* an exception using the `raise` keyword. In effect the lines of code following the `raise ...`  call will not execute.\n\n- An exception may be *caught* using a `try ... except ... end` construction. Catching an exception means that you somehow \"deal\" with exception, and the following code should execute as usual, the exception is no longer propagated upward.\n+\nNote: If an exception is raised but never caught, it will cause the entire application to stop with an error.\n+\n** But in LCL applications, the exceptions are always caught around events (and cause LCL dialog box) if you don't catch them earlier.\n** In _Castle Game Engine_ applications using `CastleWindow`, we similarly always catch exceptions around your events (and display proper dialog box).\n** So it is not so easy to make an exception that is _not caught anywhere_ (not caught in your code, LCL code, CGE code...).\n\n- Although an exception breaks the execution, you can use the `try ... finally ... end` construction to execute some code *always*, even if the code was interrupted by an exception.\n+\nThe `try ... finally ... end` construction also works when code is interrupted by `Break` or `Continue` or `Exit` keywords. The point is to always execute code in the `finally` section.\n\nAn \"exception\" is, in general, any class instance.\n\n- The compiler does not enforce any particular class. You just must call `raise XXX` where `XXX` is an instance of any class. Any class (so, anything descending from `TObject`) is fine.\n\n- It is a standard convention for exception classes to descend from a special `Exception` class. The `Exception` class extends `TObject`, adding a string `Message` property and a constructor to easily set this property. All exceptions raised by the standard library descend from `Exception`. We advise to follow this convention.\n\n- Exception classes (by convention) have names that start with `E`, not `T`. Like `ESomethingBadHappened`.\n\n- The compiler will automatically free exception object when it is handled. Don't free it yourself.\n+\nIn most cases, you just construct the object at the same time when you call `raise`, like `raise ESomethingBadHappened.Create('Description of what bad thing happened.')`.\n\n### Raising\n\nIf you want to raise your own exception, declare it and call `raise ...` when appropriate:\n\n[source,pascal]\n----\ntype\n  EInvalidParameter = class(Exception);\n\nfunction ReadParameter: String;\nbegin\n  Result := Readln;\n  if Pos(' ', Result) <> 0 then\n    raise EInvalidParameter.Create('Invalid parameter, space is not allowed');\nend;\n----\n\nNote that the expression following the `raise` should be a valid class instance to raise. You will almost always create the exception instance here.\n\nYou can also use the `CreateFmt` constructor, which is a comfortable shortcut to `Create(Format(MessageFormat, MessageArguments))`. This is a common way to provide more information to the exception message. We can improve the previous example like this:\n\n[source,pascal]\n----\ntype\n  EInvalidParameter = class(Exception);\n\nfunction ReadParameter: String;\nbegin\n  Result := Readln;\n  if Pos(' ', Result) <> 0 then\n    raise EInvalidParameter.CreateFmt('Invalid parameter %s, space is not allowed', [Result]);\nend;\n----\n\n### Catching\n\nYou can catch an exception like this:\n\n[source,pascal]\n----\nvar\n  Parameter1, Parameter2, Parameter3: String;\nbegin\n  try\n    WriteLn('Input 1st parameter:');\n    Parameter1 := ReadParameter;\n    WriteLn('Input 2nd parameter:');\n    Parameter2 := ReadParameter;\n    WriteLn('Input 3rd parameter:');\n    Parameter3 := ReadParameter;\n  except\n    // capture EInvalidParameter raised by one of the above ReadParameter calls\n    on EInvalidParameter do\n      WriteLn('EInvalidParameter exception occurred');\n  end;\nend;\n----\n\nTo improve the above example, we can declare the name for the exception instance (we will use `E` in the example). This way we can print the exception message:\n\n[source,pascal]\n----\ntry\n...\nexcept\n  on E: EInvalidParameter do\n    WriteLn('EInvalidParameter exception occurred with message: ' + E.Message);\nend;\n----\n\nOne could also test for multiple exception classes:\n\n[source,pascal]\n----\ntry\n...\nexcept\n  on E: EInvalidParameter do\n    WriteLn('EInvalidParameter exception occurred with message: ' + E.Message);\n  on E: ESomeOtherException do\n    WriteLn('ESomeOtherException exception occurred with message: ' + E.Message);\nend;\n----\n\nYou can also react to any exception raised, if you don't use any `on` expression:\n\n[source,pascal]\n----\ntry\n...\nexcept\n  WriteLn('Warning: Some exception occurred');\nend;\n// WARNING: DO NOT FOLLOW THIS EXAMPLE WITHOUT READING A WARNING BELOW\n// ABOUT \"CAPTURING ALL EXCEPTIONS\"\n----\n\nIn general _you should only catch exceptions of a specific class, that signal a particular problem that you know what to do with_. Be careful with catching exceptions of a general type (like catching any `Exception` or any `TObject`), as you may easily catch too much, and later cause troubles when debugging other problems. As in all programming languages with exceptions, the good rule to follow is to _never capture an exception that you do not know how to handle_. In particular, do not capture an exception just as a simple workaround of the problem, without investigating first _why_ the exception occurs.\n\n- Does the exception indicate a problem in user input? Then you should report it to user.\n\n- Does the exception indicate a bug in your code? Then you should fix the code, to avoid the exception from happening at all.\n\nAnother way to capture all exceptions is to use:\n\n[source,pascal]\n----\ntry\n...\nexcept\n  on E: TObject do\n    WriteLn('Warning: Some exception occurred');\nend;\n// WARNING: DO NOT FOLLOW THIS EXAMPLE WITHOUT READING A WARNING ABOVE\n// ABOUT \"CAPTURING ALL EXCEPTIONS\"\n----\n\nAlthough usually it is enough to capture `Exception`:\n\n[source,pascal]\n----\ntry\n...\nexcept\n  on E: Exception do\n    WriteLn('Warning: Some exception occurred: ' + E.ClassName + ', message: ' + E.Message);\nend;\n// WARNING: DO NOT FOLLOW THIS EXAMPLE WITHOUT READING A WARNING ABOVE\n// ABOUT \"CAPTURING ALL EXCEPTIONS\"\n----\n\nYou can \"re-raise\" the exception in the `except ... end` block, if you decide so. You can just do `raise E` if the exception instance is `E`, you can also just use parameter-less `raise`. For example:\n\n[source,pascal]\n----\ntry\n...\nexcept\n  on E: EInvalidSoundFile do\n  begin\n    if E.InvalidUrl = 'http://example.com/blablah.wav' then\n      WriteLn('Warning: loading http://example.com/blablah.wav failed, ignore it')\n    else\n      raise;\n  end;\nend;\n----\n\nNote that, although the exception is an instance of an object, you should never manually free it after raising. The compiler will generate proper code that makes sure to free the exception object once it's handled.\n\n### Finally (doing things regardless of whether an exception occurred)\n\nOften you use `try .. finally .. end` construction to free an instance of some object, regardless of whether an exception occurred when using this object. The way to write it looks like this:\n\n[source,pascal]\n----\nprocedure MyProcedure;\nvar\n  MyInstance: TMyClass;\nbegin\n  MyInstance := TMyClass.Create;\n  try\n    MyInstance.DoSomething;\n    MyInstance.DoSomethingElse;\n  finally\n    FreeAndNil(MyInstance);\n  end;\nend;\n----\n\nThis always works, and does not cause memory leaks, even if `MyInstance.DoSomething` or `MyInstance.DoSomethingElse` raise an exception.\n\nNote that this takes into account that local variables, like `MyInstance` above, have undefined values (may contain random \"memory garbage\") before the first assignment. That is, writing something like this would _not_ be valid:\n\n[source,pascal]\n----\n// INCORRECT EXAMPLE:\nprocedure MyProcedure;\nvar\n  MyInstance: TMyClass;\nbegin\n  try\n    CallSomeOtherProcedure;\n    MyInstance := TMyClass.Create;\n    MyInstance.DoSomething;\n    MyInstance.DoSomethingElse;\n  finally\n    FreeAndNil(MyInstance);\n  end;\nend;\n----\n\nThe above example is not valid: if an exception occurs within `TMyClass.Create` (a constructor may also raise an exception), or within the `CallSomeOtherProcedure`, then the `MyInstance` variable is not initialized. Calling `FreeAndNil(MyInstance)` will try to call destructor of `MyInstance`, which will most likely crash with _Access Violation (Segmentation Fault)_ error. In effect, one exception causes another exception, which will make the error report not very useful: you will not see the message of the original exception.\n\nSometimes it is justified to fix the above code by first initializing all local variables to `nil` (on which calling `FreeAndNil` is safe, and will not do anything). This makes sense if you free a *lot* of class instances. So the two code examples below work equally well:\n\n[source,pascal]\n----\nprocedure MyProcedure;\nvar\n  MyInstance1: TMyClass1;\n  MyInstance2: TMyClass2;\n  MyInstance3: TMyClass3;\nbegin\n  MyInstance1 := TMyClass1.Create;\n  try\n    MyInstance1.DoSomething;\n\n    MyInstance2 := TMyClass2.Create;\n    try\n      MyInstance2.DoSomethingElse;\n\n      MyInstance3 := TMyClass3.Create;\n      try\n        MyInstance3.DoYetAnotherThing;\n      finally\n        FreeAndNil(MyInstance3);\n      end;\n    finally\n      FreeAndNil(MyInstance2);\n    end;\n  finally\n    FreeAndNil(MyInstance1);\n  end;\nend;\n----\n\nIt is probably more readable in the form below:\n\n[source,pascal]\n----\nprocedure MyProcedure;\nvar\n  MyInstance1: TMyClass1;\n  MyInstance2: TMyClass2;\n  MyInstance3: TMyClass3;\nbegin\n  MyInstance1 := nil;\n  MyInstance2 := nil;\n  MyInstance3 := nil;\n  try\n    MyInstance1 := TMyClass1.Create;\n    MyInstance1.DoSomething;\n\n    MyInstance2 := TMyClass2.Create;\n    MyInstance2.DoSomethingElse;\n\n    MyInstance3 := TMyClass3.Create;\n    MyInstance3.DoYetAnotherThing;\n  finally\n    FreeAndNil(MyInstance3);\n    FreeAndNil(MyInstance2);\n    FreeAndNil(MyInstance1);\n  end;\nend;\n----\n\nNOTE: In this simple example, you could also make a valid argument that the code should be split into 3 separate procedures, one calling each other.\n\nThe final section in the `try .. finally .. end` block executes in most possible scenarios when you leave the main code. Consider this:\n\n[source,pascal]\n----\ntry\n  A;\nfinally\n  B;\nend;\n----\n\nSo `B` will execute if\n\n- The `A` raised (and didn't catch) an exception.\n- Or you will call `Exit` or (if you're in the loop) `Break` or `Continue` right after calling `A`.\n- Or none of the above happened, and the code in `A` just executed without any exception, and you didn't call `Exit`, `Break` or `Continue` either.\n\nThe only way to really avoid the `B` being executed is to unconditionally interrupt the application process using `Halt` or some platform-specific APIs (like https://www.man7.org/linux/man-pages/man3/exit.3.html[libc exit on Unix]) inside `A`. Which generally should not be done -- it's more flexible to use exceptions to interrupt the application, because it allows some other code to have a chance to clean up.\n\nNOTE: The `try .. finally .. end` doesn't catch the exception. The exception will still propagate upward, and can be caught by the `try .. except .. end` block outside of this one.\n\nAn example of `try .. finally .. end` together with `Exit` calls:\n\n[source,pascal]\n----\nprocedure MyProcedure;\nbegin\n  try\n    WriteLn('Do something');\n    Exit;\n    WriteLn('This will not happen');\n  finally\n    WriteLn('This will happen regardless of whether we have left the block through Exception, Exit, Continue, Break, etc.');\n  end;\n  WriteLn('This will not happen');\nend;\n----\n\nSee the <<Exceptions>> chapter for more in-depth description of _exceptions_ including how to `raise` them and use `try ... except ... end` to catch them.\n\n### How the exceptions are displayed by various libraries\n\n- In case of Lazarus LCL, the exceptions raised during events (various callbacks assigned to `OnXxx` properties of LCL components) will be captured and will result in a nice dialog message, that allows the user to continue and stop the application. This means that your own exceptions do not \"get out\" from `Application.ProcessMessages`, so they do not automatically break the application. You can configure what happens using `TApplicationProperties.OnException`.\n\n- Similarly in case of _Castle Game Engine_ with `CastleWindow`: the exception is internally captured and results in nice error message. So exceptions do not \"get out\" from `Application.ProcessMessages`. Again, you can configure what happens using `Application.OnException`.\n\n- Some other GUI libraries may do a similar thing to above.\n\n- In case of other applications, you can configure how the exception is displayed by assigning a global callback to `OnHaltProgram`.\n\n## Run-time library\n\n### Input/output using streams\n\nModern programs should use `TStream` class and its many descendants to do input / output. It has many useful descendants, like `TFileStream`, `TMemoryStream`, `TStringStream`.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/file_stream.dpr[]\n----\n\n*In the Castle Game Engine*: You should use the `Download` function to create a stream that obtains data from any URL. Regular files, HTTP and HTTPS resources, Android assets and more are supported this way. Moreover, to open the resource inside your game data (in the `data` subdirectory) use the special `castle-data:/xxx` URL. Examples:\n\n[source,pascal]\n----\nEnableNetwork := true;\nS := Download('https://castle-engine.io/latest.zip');\n----\n\n[source,pascal]\n----\nS := Download('file:///home/michalis/my_binary_file.data');\n----\n\n[source,pascal]\n----\nS := Download('castle-data:/gui/my_image.png');\n----\n\nTo read text files, we advise using the `TCastleTextReader` class. It provides a line-oriented API, and wraps a `TStream` inside. The `TCastleTextReader` constructor can take a ready URL, or you can pass there your custom `TStream` source.\n\n[source,pascal]\n----\nText := TCastleTextReader.Create('castle-data:/my_data.txt');\ntry\n  while not Text.Eof do\n    WriteLnLog('NextLine', Text.ReadLn);\nfinally\n  FreeAndNil(Text);\nend;\n----\n\nDocumentation of all the _Castle Game Engine_ features to load and save streams, including the `Download` function and the `TCastleTextReader` class, is on https://castle-engine.io/url .\n\n\n### Containers (lists, dictionaries) using generics\n\nThe language and run-time library offer various flexible containers. There are a number of non-generic classes (like `TList` and `TObjectList` from the `Contnrs` unit), there are also dynamic arrays (`array of TMyType`). But to get the most flexibility *and* type-safety, I advise using *generic containers* for most of your needs.\n\nThe _generic containers_ give you a lot of helpful methods to add, remove, iterate, search, sort... The compiler also knows (and checks) that the container holds only items of the appropriate type.\n\n// Using these lists is a good idea, as you get type-safety, and their API is rich (there are methods to find, sort, iterate and so on). We discourage using _dynamic arrays_ (`array of X`, `SetLength(X, ...)`) as their API is poor (you can only use `SetLength` and your own type helpers). We discourage using `TList` or `TObjectList` as it will require casting your references from `TObject` to your type.\n\nThere are three libraries providing generics containers in FPC now:\n\n* `Generics.Collections` unit and friends (since FPC >= 3.2.0)\n* `FGL` unit\n* `GVector` unit and friends (together in `fcl-stl`)\n\nWe advise using the `Generics.Collections` unit. The generic containers it implements are\n\n- packed with useful features,\n\n- very efficient (in particular important for accessing dictionaries by keys),\n\n- compatible between FPC and Delphi,\n\n- the naming is consistent with other parts of the standard library (like the non-generic containers from the `Contnrs` unit).\n\n*In the Castle Game Engine*: We use the `Generics.Collections` intensively throughout the engine, and advise you to use `Generics.Collections` in your applications too!\n\nMost important classes from the `Generics.Collections` unit are:\n\nTList:: A generic list of types.\nTObjectList:: A generic list of object instances. It can \"own\" children, which means that it will free them automatically.\nTDictionary:: A generic dictionary.\nTObjectDictionary:: A generic dictionary, that can \"own\" the keys and/or values.\n// So (which means that they should be object instances, and will be automatically freed).\n\nHere's how to use a simple generic `TObjectList`:\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/generics_lists.dpr[]\n----\n\nNote that some operations require comparing two items, like sorting and searching (e.g. by `Sort` and `IndexOf` methods). The `Generics.Collections` containers use a _comparer_ for this. The _default comparer_ is reasonable for all types, even for records (in which case it compares memory contents, which is a reasonable default at least for searching using `IndexOf`).\n// It can be customized if needed.\n\nWhen sorting the list you can provide a _custom comparer_ as a parameter. The _comparer_ is a class implementing the `IComparer` interface. In practice, you usually define the appropriate callback, and use `TComparer<T>.Construct` method to wrap this callback into an `IComparer` instance. An example of doing this is below:\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/generics_sorting.dpr[]\n----\n\nThe `TDictionary` class implements a *dictionary*, also known as a *map (key -> value)*, also known as an *associative array*. Its API is a bit similar to the C# `TDictionary` class. It has useful iterators for keys, values, and pairs of key->value.\n\nAn example using a dictionary:\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/generics_dictionary.dpr[]\n----\n\nThe `TObjectDictionary` can additionally _own_ the dictionary keys and/or values, which means that they will be automatically freed. Be careful to _only own keys and/or values if they are object instances_. If you set to _\"owned\"_ some other type, like an `Integer` (for example, if your keys are `Integer`, and you include `doOwnsKeys`), you will get a nasty crash when the code executes.\n\nAn example code using the `TObjectDictionary` is below. Compile this example with _memory leak detection_, like `fpc -gl -gh generics_object_dictionary.dpr`, to see that everything is freed when program exits.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/generics_object_dictionary.dpr[]\n----\n\nIf you prefer using the `FGL` unit instead of `Generics.Collections`, the most important classes from the `FGL` unit are:\n\nTFPGList:: A generic list of types.\nTFPGObjectList:: A generic list of object instances. It can \"own\" children.\nTFPGMap:: A generic dictionary.\n\n//Use `TFPGList` for lists of primitives (or records or old-style objects), `TFPGObjectList` for a list of class instances. *In the Castle Game Engine:* You can also use `CastleGenericLists` with `TGenericStructList` for a list of records or old-style objects, this workarounds the problem of impossibility to override their operators in older FPC versions.\n\nIn `FGL` unit, the `TFPGList` can be only used for types for which the equality operator (=) is defined. For `TFPGMap` the _\"greater than\"_ (>) and _\"less than\"_ (<) operators must be defined for the key type. If you want to use these lists with types that don't have built-in comparison operators (e.g. with records), you have to overload their operators as shown in the <<Operator overloading>>.\n\n*In the Castle Game Engine* we include a unit `CastleGenericLists` that adds `TGenericStructList` and `TGenericStructMap` classes. They are similar to `TFPGList` and `TFPGMap`, but they do not require a definition of the comparison operators for the appropriate type (instead, they compare memory contents, which is often appropriate for records or method pointers). But the `CastleGenericLists` unit is deprecated since the engine version 6.3, as we advise using `Generics.Collections` instead.\n\nIf you want to know more about the generics, see <<Generics>>.\n\n### Cloning: TPersistent.Assign\n\nCopying the class instances by a simple assignment operator copies the *reference*.\n\n[source,pascal]\n----\nvar\n  X, Y: TMyObject;\nbegin\n  X := TMyObject.Create;\n  Y := X;\n  // X and Y are now two pointers to the same data\n  Y.MyField := 123; // this also changes X.MyField\n  FreeAndNil(X);\nend;\n----\n\nTo copy the *class instance contents*, the standard approach is to derive your class from `TPersistent`, and override its `Assign` method. Once it's implemented properly in `TMyObject`, you use it like this:\n\n[source,pascal]\n----\nvar\n  X, Y: TMyObject;\nbegin\n  X := TMyObject.Create;\n  Y := TMyObject.Create;\n  Y.Assign(X);\n  Y.MyField := 123; // this does not change X.MyField\n  FreeAndNil(X);\n  FreeAndNil(Y);\nend;\n----\n\nTo make it work, you need to implement the `Assign` method to actually copy the fields you want. You should carefully implement the `Assign` method, to copy from a class that may be a descendant of the current class.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/persistent.dpr[]\n----\n\nSometimes it's more comfortable to alternatively override the `AssignTo` method in the source class, instead of overriding the `Assign` method in the destination class.\n\nBe careful when you call `inherited` in the overridden `Assign` implementation. There are two situations:\n\nYour class is a direct descendant of the `TPersistent` class. (Or, it's not a direct descendant of `TPersistent`, but no ancestor has overridden the `Assign` method.)::\n\n  In this case, your class should use the `inherited` keyword (to call the `TPersistent.Assign`) _only if you cannot handle the assignment in your code_.\n\nYour class descends from some class that has already overridden the `Assign` method.::\n\n  In this case, your class should _always_ use the `inherited` keyword (to call the ancestor `Assign`). In general, calling `inherited` in overridden methods is _usually_ a good idea.\n\nTo understand the reason behind the above rule (when you should call, and when you should _not_ call `inherited` from the `Assign` implementation), and how it relates to the `AssignTo` method, let's look at the `TPersistent.Assign` and `TPersistent.AssignTo` implementations:\n\n[source,pascal]\n----\nprocedure TPersistent.Assign(Source: TPersistent);\nbegin\n  if Source <> nil then\n    Source.AssignTo(Self)\n  else\n    raise EConvertError...\nend;\n\nprocedure TPersistent.AssignTo(Destination: TPersistent);\nbegin\n  raise EConvertError...\nend;\n----\n\nNOTE: This is not the *exact* implementation of `TPersistent`. I copied the FPC standard library code, but then I simplified it to hide unimportant details about the exception message.\n//The exact source code, in the FPC standard library, can be found in the `rtl/objpas/classes/persist.inc` source file. Its behavior is 100% compatible with the Delphi standard library, as far as I know.\n\nThe conclusions you can get from the above are:\n\n* _If neither `Assign` nor `AssignTo` are overridden_, then calling them will result in an exception.\n\n* Also, note that there is _no_ code in `TPersistent` implementation that automatically copies all the fields (or all the published fields) of the classes. That's why you need to do that yourself, by overriding `Assign` in all the classes. You can use RTTI (runtime type information) for that, but for simple cases you will probably just list the fields to be copied manually.\n\nWhen you have a class like `TApple`, your `TApple.Assign` implementation usually deals with copying fields that are specific to the `TApple` class (not to the `TApple` ancestor, like `TFruit`). So, the `TApple.Assign` implementation usually checks whether `Source is TApple` at the beginning, before copying apple-related fields. Then, it calls `inherited` to allow `TFruit` to handle the rest of the fields.\n\nAssuming that you implemented `TFruit.Assign` and `TApple.Assign` following the standard pattern (as shown in the example above), the effect is like this:\n\n* If you pass `TApple` instance to `TApple.Assign`, it will work and copy all the fields.\n* If you pass `TOrange` instance to `TApple.Assign`, it will work and only copy the common fields shared by both `TOrange` and `TApple`. In other words, the fields defined at `TFruit`.\n* If you pass `TWerewolf` instance to `TApple.Assign`, it will raise an exception (because `TApple.Assign` will call `TFruit.Assign` which will call `TPersistent.Assign` which raises an exception).\n\nNOTE: Remember that when descending from `TPersistent`, the default _visibility specifier_ is `published`, to allow streaming of `TPersistent` descendants. Not all field and property types are allowed in the `published` section. If you get errors related to it, and you don't care about streaming, just change the visibility to `public`. See the <<Visibility specifiers>>.\n\n## Various language features\n\n### Local (nested) routines\n\nInside a larger _routine_ (function, procedure, method) you can define a helper routine.\n\n//It has all the flexibility of a normal routine, it's just not\n//This is quite powerful feature that allows you to _easily_ split a long routine into many smaller ones.\n\nThe local routine can freely access (read and write) all the parameters of a parent, _and all the local variables of the parent that were declared above it_. This is very powerful. It often allows to split long routines into a couple of small ones without much effort (as you don't have to pass around all the necessary information in the parameters). Be careful to not overuse this feature -- if many nested functions use (and even change) the same variable of the parent, the code may get hard to follow.\n\nThese two examples are equivalent:\n\n[source,pascal]\n----\nfunction SumOfSquares(const N: Integer): Integer;\n\n  function Square(const Value: Integer): Integer;\n  begin\n    Result := Value * Value;\n  end;\n\nvar\n  I: Integer;\nbegin\n  Result := 0;\n  for I := 0 to N do\n    Result := Result + Square(I);\nend;\n----\n\nAnother version, where we let the local routine `Square` to access `I` directly:\n\n[source,pascal]\n----\nfunction SumOfSquares(const N: Integer): Integer;\nvar\n  I: Integer;\n\n  function Square: Integer;\n  begin\n    Result := I * I;\n  end;\n\nbegin\n  Result := 0;\n  for I := 0 to N do\n    Result := Result + Square;\nend;\n----\n\nLocal routines can go to any depth -- which means that you can define a local routine within another local routine. So you can go wild (but please don't go _too wild_, or the code will get unreadable:).\n\n\n\n### Callbacks (aka events, aka pointers to functions, aka procedural variables)\n\nThey allow to call a function indirectly, through to a variable. The variable can be assigned at runtime to point to any function _with matching parameter types and return types_.\n\nThe callback can be:\n\n* Normal, which means it can point to any normal routine (not a method, not local).\n+\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/callbacks.dpr[]\n----\n* A method: declare with `of object` at the end.\n+\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/callbacks_of_object.dpr[]\n----\n+\nNote that you _cannot_ pass global procedures / functions as methods. They are incompatible. If you have to provide an `of object` callback, but don't want to create a dummy class instance, you can pass <<Class methods>> as methods.\n+\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/callbacks_of_object_class_methods.dpr[]\n----\n\n* 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>>.\n\n### Anonymous functions\n\nDelphi and new FPC versions (>= 3.3.1) support:\n\n- anonymous functions (define function implementation right when you assign it to a variable or pass as an argument),\n- and function references (a new type of \"function callback\" that can accept a wide range of function types, including global functions, methods and anonymous functions).\n\nExample:\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/anon_functions_list_map_foreach.dpr[]\n----\n\nMore information:\n\n- Delphi documentation: https://docwiki.embarcadero.com/RADStudio/Sydney/en/Anonymous_Methods_in_Delphi\n\n- FPC forum post: https://forum.lazarus.freepascal.org/index.php/topic,59468.0.html\n\n- FPC feature changelog: https://wiki.freepascal.org/FPC_New_Features_Trunk#Support_for_Function_References_and_Anonymous_Functions\n\nTo get FPC 3.3.1, we recommend to use FpcUpDeluxe: https://castle-engine.io/fpcupdeluxe .\n\n### Generics\n\nA powerful feature of any modern language. The definition of something (typically, of a class) can be parameterized with another type. The most typical example is when you need to create a container (a list, dictionary, tree, graph...): you can define _a list of type T_, and then _specialize_ it to instantly get _a list of integers_, _a list of strings_, _a list of TMyRecord_, and so on.\n\nThe generics in Pascal work much like generics in C++. Which means that they are _\"expanded\"_ at specialization time, a _little_ like macros (but much safer than macros; for example, the identifiers are resolved at the time of generic definition, not at specialization, so you cannot \"inject\" any unexpected behavior when specializing the generic). In effect this means that they are very fast (can be optimized for each particular type) and work with types of any size. You can use a primitive type (integer, float) as well as a record, as well as a class when specializing a generic.\n\n// Unlike in Java, you are *not* limited to only generics of things that are a reference.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/generics.dpr[]\n----\n\nGenerics are not limited to classes, you can have generic functions and procedures as well:\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/generic_functions.dpr[]\n----\n\nSee also the <<generic-containers-section>> about important standard classes using generics.\n\n### Overloading\n\nMethods (and global functions and procedures) with the same name are allowed, as long as they have different parameters. At compile time, the compiler detects which one you want to use, knowing the parameters you pass.\n\nBy default, the overloading uses the FPC approach, which means that all the methods in given namespace (a class or a unit) are equal, and hide the other methods in namespaces with less priority. For example, if you define a class with methods `Foo(Integer)` and `Foo(string)`, and it descends from a class with method `Foo(Float)`, then the users of your new class will not be able to access the method `Foo(Float)` easily (they still can --- if they typecast the class to its ancestor type). To overcome this, use the `overload` keyword.\n\n### Preprocessor\n\nYou can use simple preprocessor directives for\n\n* conditional compilation (code depending on platform, or some custom switches),\n* to include one file in another,\n* you can also use parameter-less macros.\n\nNote that macros with parameters are not allowed. In general, you should avoid using the preprocessor stuff... unless it's really justified. The preprocessing happens before parsing, which means that you can \"break\" the normal syntax of the Pascal language. This is a powerful, but also somewhat dirty, feature.\n\n[source,pascal]\n----\nunit PreprocessorStuff;\n\n{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}\n\ninterface\n\n{$ifdef FPC}\n{ This is only defined when compiled by FPC, not other compilers (like Delphi). }\nprocedure Foo;\n{$endif}\n\n{ Define a NewLine constant. Here you can see how the normal syntax of Pascal\n  is \"broken\" by preprocessor directives. When you compile on Unix\n  (includes Linux, Android, macOS), the compiler sees this:\n\n    const NewLine = #10;\n\n  When you compile on Windows, the compiler sees this:\n\n    const NewLine = #13#10;\n\n  On other operating systems, the code will fail to compile,\n  because a compiler sees this:\n\n    const NewLine = ;\n\n  It's a *good* thing that the compilation fails in this case -- if you\n  will have to port the program to an OS that is not Unix, not Windows,\n  you will be reminded by a compiler to choose the newline convention\n  on that system. }\n\nconst\n  NewLine =\n    {$ifdef UNIX} #10 {$endif}\n    {$ifdef MSWINDOWS} #13#10 {$endif} ;\n\n{$define MY_SYMBOL}\n\n{$ifdef MY_SYMBOL}\nprocedure Bar;\n{$endif}\n\n{$define CallingConventionMacro := unknown}\n{$ifdef UNIX}\n  {$define CallingConventionMacro := cdecl}\n{$endif}\n{$ifdef MSWINDOWS}\n  {$define CallingConventionMacro := stdcall}\n{$endif}\nprocedure RealProcedureName; CallingConventionMacro; external 'some_external_library';\n\nimplementation\n\n{$include some_file.inc}\n// $I is just a shortcut for $include\n{$I some_other_file.inc}\n\nend.\n----\n\nInclude files have commonly the `.inc` extension, and are used for two purposes:\n\n* The include file may only contain other compiler directives, that \"configure\" your source code. For example you could create a file `myconfig.inc` with these contents:\n+\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/myconfig.inc[]\n----\n+\nNow you can include this file using `{$I myconfig.inc}` in all your sources.\n\n* The other common use is to split a large unit into many files, while still keeping it a single unit as far as the language rules are concerned. Do not overuse this technique -- your first instinct should be to split a single unit into multiple units, not to split a single unit into multiple include files. Nevertheless, this is a useful technique.\n  . It allows to avoid \"exploding\" the number of units, while still keeping your source code files short. For example, it may be better to have a single unit with _\"commonly used UI controls\"_ than to create _one unit for each UI control class_, as the latter approach would make the typical \"uses\" clause long (since a typical UI code will depend on a couple of UI classes). But placing all these UI classes in a single `myunit.pas` file would make it a long file, unhandy to navigate, so splitting it into multiple include files may make sense.\n//For example, *Castle Game Engine* has a unit `CastleControls` with a couple of user-interface controls, like `TCastleButton`, `TCastleLabel`, `TCastleImageControl` and more. We could split it into many units, even to _one unit per class_, as the classes are not really tightly connected. But that would often force you to have a long `uses` clause, since a lot of user-interface code will want to use a couple of control classes. So we made a practical decision to just put all _often used controls_ in a single unit.\n  . It allows to have a cross-platform unit interface with platform-dependent implementation easily. Basically you can do\n+\n[source,pascal]\n----\n{$ifdef UNIX} {$I my_unix_implementation.inc} {$endif}\n{$ifdef MSWINDOWS} {$I my_windows_implementation.inc} {$endif}\n----\n+\nSometimes this is better than writing a long code with many `{$ifdef UNIX}`, `{$ifdef MSWINDOWS}` intermixed with normal code (variable declarations, routine implementation). The code is more readable this way. You can even use this technique more aggressively, by using the `-Fi` command-line option of FPC to include some subdirectories only for specific platforms. Then you can have many version of include file `{$I my_platform_specific_implementation.inc}` and you simply include them, letting the compiler find the correct version.\n\n### Records\n\nA _record_ is just a container for other variables. It's like a much, much simplified _class_: there is no inheritance or virtual methods. It is like a _structure_ in C-like languages.\n\nIf you use the `{$modeswitch advancedrecords}` directive, records *can* have methods and visibility specifiers. In general, language features that are available for classes, and _do not break the simple predictable memory layout of a record_, are then possible.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/records.dpr[]\n----\n\nIn modern Object Pascal, your first instinct should be to design a `class`, not a `record` -- because classes are packed with useful features, like constructors and inheritance.\n\nBut records are still very useful when you need speed or a predictable memory layout:\n\n* Records do not have any constructor or destructor. You just define a variable of a record type. It has undefined contents (memory garbage) at the beginning (except auto-managed types, like strings; they are guaranteed to be initialized to be empty, and finalized to free the reference count). So you have to be more careful when dealing with records, but it gives you some performance gain.\n* Arrays of records are nicely linear in memory, so they are cache-friendly.\n* The memory layout of records (size, padding between fields) is clearly defined in some situations: when you request the _C layout_, or when you use `packed record`. This is useful:\n** to communicate with libraries written in other programming languages, when they expose an API based on records,\n** to read and write binary files,\n** to implement dirty low-level tricks (like unsafe typecasting one type to another, being aware of their memory representation).\n* Records can also have `case` parts, which work like _unions_ in C-like languages. They allows to treat the same memory piece as a different type, depending on your needs. As such, this allows for greater memory efficiency in some cases. And it allows for more _dirty, low-level unsafe tricks_:)\n\n### Variant records and related concepts\n\nThe concept _variant_ may refer to 3 distinct (though, deep down related) things in Pascal:\n\n#### Variant records\n\n_Variant records_ allow to define a section at the end of your record where the same memory can be accessed by a few different names/types.\n\nThis is described on https://en.wikipedia.org/wiki/Tagged_union on Wikipedia. _\"Union\"_ is more common name for this in other languages. See also https://www.freepascal.org/docs-html/ref/refsu15.html .\n\nExample:\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/variant_in_record.dpr[]\n----\n\n#### Variant type\n\n`Variant` is a special type in Pascal that underneath can hold values of various types. Moreover, operators are defined to allow operating on them and converting their values at run-time.\n\nThe effect is a bit similar to scripting programming languages with dynamic typing.\n\nDo not use them without consideration: things are a bit less safe (you don't control types, conversions happen implicitly). Also there's a small performance hit, since all operations need to check and synchronize the types at run-time.\n\nBut sometimes it does make sense. Namely, when you have to process data that intrinsically indeed may have different types, and you only know those types at runtime. E.g. when you want to process result of SQL `select * from some_table` in a generic database viewer (not knowing table structure at compile-time).\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/variant_types.dpr[]\n----\n\nNOTE: Technically, `Variant` is realized using `TVarData` internal type, which is a record with variants. So these concepts are connected. But you should *not need to know this*, you should not use `TVarData` explicitly.\n\n#### TVarRec in array of const\n\nWhen you use `array of const` special parameter type, it is passed as an array of `TVarRec`. See\n\n- `TVarRec` in FPC: https://www.freepascal.org/docs-html/rtl/system/tvarrec.html\n\n- `TVarRec` in Delphi: https://docwiki.embarcadero.com/Libraries/Sydney/en/System.TVarRec\n\nThis is useful to pass to a routine parameters of arbitrary (not known at compile-time) types. For example, to implement routines like standard `Format` (similar to `sprintf` in C) or _Castle Game Game_ `WriteLnLog` / `WriteLnWarning`.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/array_of_const.dpr[]\n----\n\n### Old-style objects\n\nIn the old days, Turbo Pascal introduced another syntax for class-like functionality, using the `object` keyword. It's somewhat of a blend between the concept of a `record` and a modern `class`.\n\n* The old-style objects can be allocated / freed, and during that operation you can call their constructor / destructor.\n* But they can also be simply declared and used, like records. A simple `record` or `object` type is not a reference (pointer) to something, it's simply the data. This makes them comfortable for small data, where calling allocation / free would be bothersome.\n//It also makes them fast -- a list of such structures is nicely linear in memory, iterating over it doesn't involve jumping over pointers. Also, their memory layout is defined in _some_ situations (packed records, or records with C layout), which makes them suitable to pass to external APIs, like OpenGL.\n* Old-style objects offer inheritance and virtual methods, although with small differences from the modern classes. Be careful -- _bad things_ will happen if you try to use an object without calling its constructor, and the object has virtual methods.\n\nIt's discouraged to use the old-style objects in most cases. Modern _classes_ provide much more functionality. And when needed, records (including _advanced records_) can be used for performance. These concepts are usually a better idea than old-style objects.\n\n### Pointers\n\nYou can create a _pointer_ to any other type. The pointer to type `TMyRecord` is declared as `^TMyRecord`, and by convention is called `PMyRecord`. This is a traditional example of a linked list of integers using records:\n\n[source,pascal]\n----\ntype\n  PMyRecord = ^TMyRecord;\n  TMyRecord = record\n    Value: Integer;\n    Next: PMyRecord;\n  end;\n----\n\nNote that the definition is recursive (type `PMyRecord` is defined using type `TMyRecord`, while `TMyRecord` is defined using `PMyRecord`). It is allowed to define a pointer type to a _not-yet-defined type_, as long as it will be resolved within the same `type` block.\n\nYou can allocate and free pointers using the `New` / `Dispose` methods, or (more low-level, not type-safe) `GetMem` / `FreeMem` methods. You dereference the pointer (to access the stuff _pointed by_) you append the `^` operator (e.g. `MyInteger := MyPointerToInteger^`). To make the inverse operation, which is to _get a pointer of an existing variable_, you prefix it with `@` operator (e.g. `MyPointerToInteger := @MyInteger`).\n\nThere is also an untyped `Pointer` type, similar to `void*` in C-like languages. It is completely unsafe, and can be typecasted to any other pointer type.\n\nRemember that a _class instance_ is also in fact a pointer, although it doesn't require any `^` or `@` operators to use it.\n//That's why it's called a _reference_.\nA linked list using classes is certainly possible, it would simply be this:\n\n[source,pascal]\n----\ntype\n  TMyClass = class\n    Value: Integer;\n    Next: TMyClass;\n  end;\n----\n\n### Operator overloading\n\nYou can override the meaning of many language operators, for example to allow addition and multiplication of your custom types.\n\nBoth FPC and Delphi support overloading operators by defining `class operator` methods inside advanced records. Like this:\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/operator_overloading_class_operator.dpr[]\n----\n\nNOTE: With FPC, make sure to tell the compiler you use the \"advanced records\" feature by `{$modeswitch advancedrecords}`.\n\nTake a look at the documentation to learn all possible operators that can be overloaded:\n\n- https://wiki.freepascal.org/Operator_overloading[FPC operator overloading]\n- https://docwiki.embarcadero.com/RADStudio/Sydney/en/Operator_Overloading_%28Delphi%29[Delphi operator overloading]\n\nFPC supports also an alternative syntax to overload operators, by defining a global function like `operator*`. For example:\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/operator_overloading.dpr[]\n----\n\nThis approach (global `operator` functions) can be used to define operators on classes too. Since you usually create new instances of your classes inside the operator function, the caller must remember to free the result.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/operator_overloading_classes.dpr[]\n----\n\nYou can override operators on records too using the global `operator` functions. This is usually easier than overloading them for classes, as the caller doesn't have to deal then with memory management.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/operator_overloading_records.dpr[]\n----\n\nHowever, for records, we don't advise to use the global `operator` functions. Instead, use `{$modeswitch advancedrecords}` and override operators as `class operator` inside the record. Reasons:\n\n- This is compatible with Delphi.\n\n- This allows to use generic classes that depend on some operator's existence (like `TFPGList`, that depends on the equality operator being available) with such records. Otherwise the \"global\" definition of an operator (not inside the record) would not be found (because it's not available at the code that implements the `TFPGList`), and you could not specialize a list like `specialize TFPGList<TMyRecord>`.\n\n[source,pascal]\n----\ninclude::modern_pascal_code_samples/operator_overloading_records_lists.dpr[]\n----\n\n\n*(Tutorial continues at the canonical URL; extract truncated for length.)*\n","body_html":"<h1 id=\"modern-object-pascal-introduction-for-programmers\">Modern Object Pascal Introduction for Programmers</h1>\n<p>include::common.adoc[]\n:description: Modern Object Pascal Introduction: units, classes, generics, memory management, exceptions and more.\n:cge-social-share-image: pascal_code_sample.png</p>\n<h2 id=\"why-this-book\">Why this book</h2>\n<p>I wanted to describe the <em>modern Object Pascal</em>: programming language with classes, units, generics, interfaces and other modern features you expect. I wanted to show how all the language features, basic and advanced, connect together into a consistent whole.</p>\n<p>I also wanted this book to be practical and concise to fellow developers. As such, I assume you already have some programming experience, and we can talk about things like <em>&quot;how to declare a variable&quot;</em> and avoid a lengthy explanation <em>&quot;what even is a variable and what is its purpose&quot;</em>. When covering the basics, I will give a brief description, and then move on, like this: a <em>variable</em> is a container for some value; the container has a name; the value it holds may change over time.</p>\n<p>I emphasize the word <em>modern</em> in <em>modern Object Pascal</em>.\nThat&#39;s because <em>Pascal</em> has evolved a <em>lot</em>, and it&#39;s quite different from e.g. <em>Turbo Pascal</em> that many people learned in schools long time ago. Feature-wise, <em>modern Pascal</em> is quite similar to C++ or Java or C#.</p>\n<ul><li>It has all the modern features you expect -- classes, units, interfaces, generics...</li><li>It&#39;s compiled to a fast, native code,</li><li>It&#39;s very type safe,</li><li>High-level but can also be low-level if you need it to be.</li></ul>\n<p>For more reasoning about <a href=\"https://castle-engine.io/why_pascal[why\" rel=\"nofollow ugc noopener\">https://castle-engine.io/why_pascal[why</a> use Pascal, see here].</p>\n<p>We also have an active ecosystem of tools and libraries. To name just a few:</p>\n<ul><li>Pascal has an excellent, portable and open-source compiler called the <em>Free Pascal Compiler</em>, <a href=\"http://freepascal.org/\" rel=\"nofollow ugc noopener\">http://freepascal.org/</a> .</li><li>And an accompanying IDE (editor, debugger, a library of visual components, form designer) called <em>Lazarus</em> <a href=\"http://lazarus.freepascal.org/\" rel=\"nofollow ugc noopener\">http://lazarus.freepascal.org/</a> .</li><li>There&#39;s also a proprietary and commercial compiler and IDE <em>Delphi</em> <a href=\"https://www.embarcadero.com/products/Delphi\" rel=\"nofollow ugc noopener\">https://www.embarcadero.com/products/Delphi</a> .</li><li>There&#39;s a lot of libraries (for both FPC and Delphi) available, see <a href=\"https://github.com/Fr0sT-Brutal/awesome-pascal\" rel=\"nofollow ugc noopener\">https://github.com/Fr0sT-Brutal/awesome-pascal</a> .</li><li>We also support existing editors like <em>VS Code</em>, see <a href=\"https://castle-engine.io/vscode\" rel=\"nofollow ugc noopener\">https://castle-engine.io/vscode</a> .</li><li>Myself, I&#39;m the creator of <em>Castle Game Engine</em>, <a href=\"https://castle-engine.io/\" rel=\"nofollow ugc noopener\">https://castle-engine.io/</a> , which is an open-source 3D and 2D game engine using modern Pascal to create games on many platforms (Windows, Linux, FreeBSD, macOS, Android, iOS, Nintendo Switch, WebGL).</li></ul>\n<h2 id=\"basics\">Basics</h2>\n<h3 id=\"hello-world-program\">&quot;Hello world&quot; program</h3>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/hello_world.dpr[]</p>\n<hr />\n<p>This is a complete program that you can <em>compile</em> and <em>run</em>.</p>\n<ul><li>If you use the command-line FPC, just create a new file <code>myprogram.dpr</code> and execute <code>fpc myprogram.dpr</code>.</li><li>If you use <em>Lazarus</em>, create a new project (menu <em>&quot;Project -&gt; New Project -&gt; Simple Program&quot;</em>). Paste this as the program source code. Compile using the menu item <em>&quot;Run -&gt; Compile&quot;</em> (or use shortcut <em>Ctrl + F9</em>).</li><li>If you use <em>Delphi</em>, also create a new project (menu <em>&quot;File -&gt; New -&gt; Console Application - Delphi&quot;</em>). Paste this as the program source code. Compile using the menu item <em>&quot;Project -&gt; Compile&quot;</em> (or use shortcut <em>Ctrl + F9</em>).</li></ul>\n<p>This is a command-line program, so just run the compiled executable from the command-line.</p>\n<p>NOTE: You can also run it from <em>Lazarus</em> or <em>Delphi</em> IDE using the <em>&quot;Run&quot;</em> menu item (shortcut F9 in both IDEs). In this case, note that the console will appear and disappear quickly. The simplest way to avoid it is to add <code>Readln</code> (wait for <em>Enter</em>) at the end of the application.</p>\n<p>The rest of this article talks about the Object Pascal language, so don&#39;t expect to see anything more fancy than the command-line stuff. If you want to see something cool, just create a new GUI project in <em>Lazarus</em> (<em>&quot;Project -&gt; New Project -&gt; Application&quot;</em>) or <em>Delphi</em> (<em>&quot;File -&gt;  New -&gt; Multi-Device Application&quot;</em>).\n//Play around, drop some buttons on the form, handle their events (like <code>OnClick</code>).\nVoila -- a working GUI application, cross-platform, with native look everywhere, using a comfortable visual component library.</p>\n<p>The Pascal compilers come with lots of standard units for networking, GUI, database, file formats (XML, json, images...), threading and everything else you may need. I already mentioned my cool <em>Castle Game Engine</em> earlier:)\n// The libraries created in other languages (dll, so, dylib) can be easily used from FPC too (and for most of them, you&#39;ll find ready &quot;header&quot; units, and even units that wrap them in more modern object-oriented API).</p>\n<h3 id=\"compilers-and-fpc-syntax-modes\">Compilers and FPC &quot;syntax modes&quot;</h3>\n<p>This book, all the text and Pascal examples, has been written to support two modern Pascal compilers:</p>\n<ol><li><em>Free Pascal Compiler (FPC)</em>, open-source Pascal compiler, used also by the <em>Lazarus</em> IDE.</li><li><em>Delphi</em>, a proprietary Pascal compiler from Embarcadero.</li></ol>\n<p>In this book, we support fully both compilers.\n//TMI:Just like in <em>Castle Game Engine</em>, we support them both, and it&#39;s your choice which one do you prefer.\n//TMI: Our <em>continuous integration</em> (see <a href=\"https://castle-engine.io/github_actions\" rel=\"nofollow ugc noopener\">https://castle-engine.io/github_actions</a>) makes sure all samples really compile with both compilers.</p>\n<p>To complicate matters a bit, FPC compiler has multiple &quot;syntax modes&quot;. In this book, we decided to show the <em>ObjFpc</em> syntax mode, which is recommended by the FPC developers and is the default for new Pascal projects created using <em>Lazarus</em> or <em>Castle Game Engine</em>. It&#39;s a bit different from the <em>Delphi</em> syntax mode, which is most compatible with Pascal language as implemented by <em>Delphi</em>. We <a href=\"https://github.com/modern-pascal/modern-pascal-introduction/wiki/Some-differences-betwen-FPC-ObjFpc-mode-and-Delphi-\" rel=\"nofollow ugc noopener\">https://github.com/modern-pascal/modern-pascal-introduction/wiki/Some-differences-betwen-FPC-ObjFpc-mode-and-Delphi-</a>(and-FPC-Delphi-mode)[wrote a detailed comparison here].</p>\n<p>But you don&#39;t want to read about these differences now, if you&#39;re just starting to learn Pascal!</p>\n<p>The differences are minor, both between compilers and between FPC <em>ObjFpc</em> mode and <em>Delphi</em> mode. Just be aware you may see some <code>{$ifdef FPC} ... {$endif}</code> clauses in the examples, that make the code valid for both <em>FPC ObjFpc mode</em> and <em>Delphi</em>. Using <code>{$ifdef FPC_OBJFPC} ... {$endif}</code> in some of these cases would be more precise, but look even more complicated. If your project targets only one of these compilers, you can simplify your code, just pick the variant for your compiler and remove the <code>{$ifdef ...}</code>, <code>{$endif}</code> stuff.</p>\n<h3 id=\"functions-procedures-primitive-types\">Functions, procedures, primitive types</h3>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/functions_primitives.dpr[]</p>\n<hr />\n<p>To return a value from a function, assign something to the magic <code>Result</code> variable. You can read and set the <code>Result</code> freely, just like a local variable.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>function MyFunction(const S: string): string;\nbegin\n  Result := S + &#39;something&#39;;\n  Result := Result + &#39; something more!&#39;;\n  Result := Result + &#39; and more!&#39;;\nend;</p>\n<hr />\n<p>You can also treat the function name (like <code>MyFunction</code> in example above) as the variable, to which you can assign. But I would discourage it in new code, as it looks &quot;fishy&quot; when used on the right side of the assignment expression. Just use <code>Result</code> always when you want to read or set the function result.</p>\n<p>If you want to call the function itself recursively, you can of course do it. If you&#39;re calling a parameter-less function recursively, be sure to specify the parenthesis <code>()</code> (even though in Pascal you can usually omit the parentheses for a parameter-less function), this makes a recursive call to a parameter-less function different from accessing this function&#39;s current result. Like this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>function SumIntegersUntilZero: Integer;\nvar\n  I: Integer;\nbegin\n  ReadLn(I);\n  Result := I;\n  if I &lt;&gt; 0 then\n    Result := Result + SumIntegersUntilZero();\nend;</p>\n<hr />\n<p>You can call <code>Exit</code> to end the execution of the procedure or function before it reaches the final <code>end;</code>. If you call parameter-less <code>Exit</code> in a function, it will return the last thing you set as <code>Result</code>. You can also use <code>Exit(X)</code> construct, to set the function result and exit <em>now</em> -- this is just like <code>return X</code> construct in C-like languages.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>function AddName(const ExistingNames, NewName: string): string;\nbegin\n  if ExistingNames = &#39;&#39; then\n    Exit(NewName);\n  Result := ExistingNames + &#39;, &#39; + NewName;\nend;</p>\n<hr />\n<p>Note that the function result can be discarded. Any function may be used just like a procedure. This makes sense if the function has some <em>side effect</em> (e.g. it modifies a global variable) besides calculating the result. For example:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>var\n  Count: Integer;\n  MyCount: Integer;</p>\n<p>function CountMe: Integer;\nbegin\n  Inc(Count);\n  Result := Count;\nend;</p>\n<p>begin\n  Count := 10;\n  CountMe; // the function result is discarded, but the function is executed, Count is now 11\n  MyCount := CountMe; // use the result of the function, MyCount equals to Count which is now 12\nend.</p>\n<hr />\n<h3 id=\"testing-if\">Testing (if)</h3>\n<p>Use <code>if .. then</code> or <code>if .. then .. else</code> to run some code when some condition is satisfied. Unlike in the C-like languages, in Pascal you don&#39;t have to wrap the condition in parenthesis.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>var\n  A: Integer;\n  B: boolean;\nbegin\n  if A &gt; 0 then\n    DoSomething;</p>\n<p>  if A &gt; 0 then\n  begin\n    DoSomething;\n    AndDoSomethingMore;\n  end;</p>\n<p>  if A &gt; 10 then\n    DoSomething\n  else\n    DoSomethingElse;</p>\n<p>  // equivalent to above\n  B := A &gt; 10;\n  if B then\n    DoSomething\n  else\n    DoSomethingElse;\nend;</p>\n<hr />\n<p>The <code>else</code> is paired with the last <code>if</code>. So this works as you expect:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>if A &lt;&gt; 0 then\n  if B &lt;&gt; 0 then\n    AIsNonzeroAndBToo\n  else\n    AIsNonzeroButBIsZero;</p>\n<hr />\n<p>While the example with nested <code>if</code> above is correct, it is often better to place the nested <code>if</code> inside a <code>begin</code> ... <code>end</code> block in such cases. This makes the code more obvious to the reader, and it will remain obvious even if you mess up the indentation. The improved version of the example is below. When you add or remove some <code>else</code> clause in the code below, it&#39;s obvious to which condition it will apply (to the <code>A</code> test or the <code>B</code> test), so it&#39;s less error-prone.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>if A &lt;&gt; 0 then\nbegin\n  if B &lt;&gt; 0 then\n    AIsNonzeroAndBToo\n  else\n    AIsNonzeroButBIsZero;\nend;</p>\n<hr />\n<h3 id=\"logical-relational-and-bit-wise-operators\">Logical, relational and bit-wise operators</h3>\n<p>The <em>logical operators</em> are called <code>and</code>, <code>or</code>, <code>not</code>, <code>xor</code>. Their meaning is probably obvious (search for <em>&quot;exclusive or&quot;</em> if you&#39;re unsure what <em>xor</em> does:)). They take <em>boolean arguments</em>, and return a <em>boolean</em>. They can also act as <em>bit-wise operators</em> when both arguments are integer values, in which case they return an integer.</p>\n<p>The <em>relational (comparison)</em> operators are <code>=</code>, <code>&lt;&gt;</code>, <code>&gt;</code>, <code>&lt;</code>, <code>\\&lt;=</code>, <code>&gt;=</code>. If you&#39;re accustomed to C-like languages, note that in Pascal you compare two values (check are they equal) using a single equality character <code>A = B</code> (unlike in C where you use <code>A == B</code>). The special <em>assignment</em> operator in Pascal is <code>:=</code>.</p>\n<p>The <em>logical (or bit-wise) operators have a higher precedence than relational operators</em>. You may need to use parenthesis around some expressions to have the desired order of the calculations.</p>\n<p>For example this is a compilation error:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>var\n  A, B: Integer;\nbegin\n  if A = 0 and B &lt;&gt; 0 then ... // INCORRECT example</p>\n<hr />\n<p>The above fails to compile, because the compiler first wants to perform a bit-wise <code>and</code> in the middle of the expression: <code>(0 and B)</code>. This is a bit-wise operation which returns an integer value. Then the compiler applies <code>=</code> operator which yields a boolean value <code>A = (0 and B)</code>. And finally the <em>&quot;type mismatch&quot;</em> error is risen after trying to compare the boolean value <code>A = (0 and B)</code> and integer value <code>0</code>.</p>\n<p>This is correct:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>var\n  A, B: Integer;\nbegin\n  if (A = 0) and (B &lt;&gt; 0) then ...</p>\n<hr />\n<p>The <em>short-circuit evaluation</em> is used. Consider this expression:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>if MyFunction(X) and MyOtherFunction(Y) then...</p>\n<hr />\n<ul><li>It&#39;s guaranteed that <code>MyFunction(X)</code> will be evaluated first.</li><li>And if <code>MyFunction(X)</code> returns <code>false</code>, then the value of expression is known (the value of <code>false and whatever</code> is always <code>false</code>), and <code>MyOtherFunction(Y)</code> will not be executed at all.</li><li>Analogous rule is for <code>or</code> expression. There, if the expression is known to be <code>true</code> (because the 1st operand is <code>true</code>), the 2nd operand is not evaluated.</li><li><p>This is particularly useful when writing expressions like</p><p>+\n[source,pascal]</p></li></ul>\n<hr />\n<p>if (A &lt;&gt; nil) and A.IsValid then...</p>\n<hr />\n<p>+\nThis will work OK, even when <code>A</code> is <code>nil</code>. The keyword <code>nil</code> is a pointer equal to zero (when represented as a number). It is called a <em>null pointer</em> in many other programming languages.</p>\n<p>// * Using <code>and</code> between two boolean values is a logical <code>and</code>, and the result is boolean. In other words, the result is <code>true</code> only if both operands are <code>true</code>, otherwise it&#39;s <code>false</code>.</p>\n<p>// * Using <code>and</code> between two integer values is a bit-wise <code>and</code>, and the result is integer. The operands are converted to have the same number of bits, and a similar rule is performed bit-by-bit, setting each bit to <code>0</code> or <code>1</code>. If you do this with potentially negative integer values, you should understand how negative numbers are encoded in memory (<em>&quot;two&#39;s complement&quot;</em>).</p>\n<h3 id=\"testing-single-expression-for-multiple-values-case\">Testing single expression for multiple values (case)</h3>\n<p>If a different action should be executed depending on the value of some expression, then the <code>case .. of .. end</code> statement is useful.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>case SomeValue of\n  0: DoSomething;\n  1: DoSomethingElse;\n  2: begin\n       IfItsTwoThenDoThis;\n       AndAlsoDoThis;\n     end;\n  3..10: DoSomethingInCaseItsInThisRange;\n  11, 21, 31: AndDoSomethingForTheseSpecialValues;\n  else DoSomethingInCaseOfUnexpectedValue;\nend;</p>\n<hr />\n<p>The <code>else</code> clause is optional (and corresponds to <code>default</code> in C-like languages). When no condition matches, and there&#39;s no <code>else</code>, then nothing happens.</p>\n<p>In you come from C-like languages, and compare this with <code>switch</code> statement in these languages, you will notice that there is no automatic <em>fall-through</em>. This is a deliberate blessing in Pascal. You don&#39;t have to remember to place <code>break</code> instructions. In every execution, <em>at most one</em> branch of the <code>case</code> is executed, that&#39;s it.</p>\n<h3 id=\"enumerated-and-ordinal-types-and-sets-and-constant-length-arrays\">Enumerated and ordinal types and sets and constant-length arrays</h3>\n<p>Enumerated type in Pascal is a very nice, opaque type. You will probably use it much more often than enums in other languages:)</p>\n<p>[source,pascal]</p>\n<hr />\n<p>type\n  TAnimalKind = (akDuck, akCat, akDog);</p>\n<hr />\n<p>The convention is to prefix the enum names with a two-letter shortcut of type name, hence <code>ak</code> = shortcut for <em>&quot;Animal Kind&quot;</em>. This is a useful convention, since the enum names are in the unit (global) namespace. So by prefixing them with <code>ak</code> prefix, you minimize the chances of collisions with other identifiers.</p>\n<p>NOTE: The collisions in names are not a show-stopper. It&#39;s Ok for different units to define the same identifier. But it&#39;s a good idea to try to avoid the collisions anyway, to keep code simple to understand and grep.</p>\n<p>NOTE: You can avoid placing enum names in the global namespace by compiler directive <code>{$scopedenums on}</code>. This means you will have to access them qualified by a type name, like <code>TAnimalKind.akDuck</code>. The need for <code>ak</code> prefix disappears in this situation, and you will probably just call the enums <code>Duck, Cat, Dog</code>. This is similar to C# enums.</p>\n<p>The fact that enumerated type is <em>opaque</em> means that it cannot be just assigned to and from an integer. However, for special use, you can use <code>Ord(MyAnimalKind)</code> to forcefully convert enum to int, or typecast <code>TAnimalKind(MyInteger)</code> to forcefully convert int to enum. In the latter case, make sure to check first whether <code>MyInteger</code> is in good range (0 to <code>Ord(High(TAnimalKind))</code>).</p>\n<p>Enumerated and ordinal types can be used as array indexes:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>type\n  TArrayOfTenStrings = array [0..9] of string;\n  TArrayOfTenStrings1Based = array [1..10] of string;</p>\n<p>  TMyNumber = 0..9;\n  TAlsoArrayOfTenStrings = array [TMyNumber] of string;</p>\n<p>  TAnimalKind = (akDuck, akCat, akDog);\n  TAnimalNames = array [TAnimalKind] of string;</p>\n<hr />\n<p>They can also be used to create sets (a bit-fields internally):</p>\n<p>[source,pascal]</p>\n<hr />\n<p>type\n  TAnimalKind = (akDuck, akCat, akDog);\n  TAnimals = set of TAnimalKind;\nvar\n  A: TAnimals;\nbegin\n  A := [];\n  A := [akDuck, akCat];\n  A := A + [akDog];\n  A := A * [akCat, akDog];\n  Include(A, akDuck);\n  Exclude(A, akDuck);\nend;</p>\n<hr />\n<h3 id=\"loops-for-while-repeat-for-in\">Loops (for, while, repeat, for .. in)</h3>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/loops.dpr[]</p>\n<hr />\n<p><em>About the <code>repeat</code> and <code>while</code> loops</em>:</p>\n<p>There are two differences between these loop types:</p>\n<ol><li>The loop condition has an opposite meaning. In <code>while .. do</code> you tell it <em>when to continue</em>, but in <code>repeat .. until</code> you tell it <em>when to stop</em>.</li><li>In case of <code>repeat</code>, <em>the condition is not checked at the beginning</em>. So the <code>repeat</code> loop always runs at least once.</li></ol>\n<p><em>About the <code>for I := ...</code> loops</em>:</p>\n<p>The <code>for I := .. to .. do ...</code> construction it similar to the C-like <code>for</code> loop. However, it&#39;s more constrained, as you cannot specify arbitrary actions/tests to control the loop iteration. This is strictly for iterating over a consecutive numbers (or other ordinal types). The only flexibility you have is that you can use <code>downto</code> instead of <code>to</code>, to make numbers go downward.</p>\n<p>In exchange, it looks clean, and is very optimized in execution. In particular, <em>the expressions for the lower and higher bound are only calculated once</em>, before the loop starts.</p>\n<p>Note that the value of the loop counter variable (<code>I</code> in this example) should be considered <em>undefined</em> after the loop has finished, due to possible optimizations. Accessing the value of <code>I</code> after the loop may cause a compiler warning. <em>Unless</em> you exit the loop prematurely by <code>Break</code> or <code>Exit</code>: in such case, the counter variable is guaranteed to retain the last value.</p>\n<p><em>About the <code>for I in ...</code> loops</em>:</p>\n<p>The <code>for I in .. do ..</code> is similar to <code>foreach</code> construct in many modern languages. It works intelligently on many built-in types:</p>\n<ul><li>It can iterate over all values in the array (example above).</li><li><p>It can iterate over all possible values of an enumerated type:</p><p>+\n[source,pascal]</p></li></ul>\n<hr />\n<p>var\n  AK: TAnimalKind;\nbegin\n  for AK in TAnimalKind do...</p>\n<hr />\n<ul><li><p>It can iterate over all items included in the set:</p><p>+\n[source,pascal]</p></li></ul>\n<hr />\n<p>var\n  Animals: TAnimals;\n  AK: TAnimalKind;\nbegin\n  Animals := [akDog, akCat];\n  for AK in Animals do ...</p>\n<hr />\n<ul><li><p>And it works on custom list types, generic or not, like <code>TObjectList</code> or <code>TFPGObjectList</code>.</p><p>+\n[source,pascal]</p></li></ul>\n<hr />\n<p>include::modern_pascal_code_samples/for_in_list.dpr[]</p>\n<hr />\n<p>+\nWe didn&#39;t yet explain the concept of classes, so the last example may not be obvious to you yet -- just carry on, it will make sense later:)</p>\n<h3 id=\"output-logging\">Output, logging</h3>\n<p>To simply output strings in Pascal, use the <code>Write</code> or <code>WriteLn</code> routine. The latter automatically adds a newline at the end.</p>\n<p>This is a &quot;magic&quot; routine in Pascal. It takes a variable number of arguments and they can have any type. They are all converted to strings when displaying, with a special syntax to specify padding and number precision.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>WriteLn(&#39;Hello world!&#39;);\nWriteLn(&#39;You can output an integer: &#39;, 3 * 4);\nWriteLn(&#39;You can pad an integer: &#39;, 666:10);\nWriteLn(&#39;You can output a float: &#39;, Pi:1:4);</p>\n<hr />\n<p>To explicitly use newline in the string, use the <code>LineEnding</code> constant (from FPC RTL). (The <em>Castle Game Engine</em> defines also a shorter <code>NL</code> constant.) Pascal strings do not interpret any special backslash sequences, so writing</p>\n<p>[source,pascal]</p>\n<hr />\n<p>WriteLn(&#39;One line.\\nSecond line.&#39;); // INCORRECT example</p>\n<hr />\n<p>doesn&#39;t work like some of you would think. This will work:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>WriteLn(&#39;One line.&#39; + LineEnding + &#39;Second line.&#39;);</p>\n<hr />\n<p>or just this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>WriteLn(&#39;One line.&#39;);\nWriteLn(&#39;Second line.&#39;);</p>\n<hr />\n<p>Note that this will only work in <em>console</em> applications. Make sure you have <code>{$apptype CONSOLE}</code> (and <em>not</em> <code>{$apptype GUI}</code>) defined in your main program file. On some operating systems it actually doesn&#39;t matter and will work always (Unix), but on some operating systems trying to write something from a GUI application is an error (Windows).</p>\n<p><em>In the Castle Game Engine:</em> use <code>WriteLnLog</code> or <code>WriteLnWarning</code>, never <code>WriteLn</code>, to print debug information. They will be always directed to some useful output. On Unix, standard output. On Windows GUI application, log file. On Android, the <em>Android logging facility</em> (visible when you use <code>adb logcat</code>). The use of <code>WriteLn</code> should be limited to the cases when you write a command-line application (like a 3D model converter / generator) and you know that the <em>standard output</em> is available.</p>\n<h3 id=\"converting-to-a-string\">Converting to a string</h3>\n<p>To convert an arbitrary number of arguments to a string (instead of just directly outputting them), you have a couple of options.</p>\n<ul><li><p>You can convert particular types to strings using specialized functions like <code>IntToStr</code> and <code>FloatToStr</code>. Furthermore, you can concatenate strings in Pascal simply by adding them. So you can create a string like this: <code>&#39;My int number is &#39; + IntToStr(MyInt) + &#39;, and the value of Pi is &#39; + FloatToStr(Pi)</code>.</p><p>** <em>Advantage</em>: Absolutely flexible. There are many <code>XxxToStr</code> overloaded versions and friends (like <code>FormatFloat</code>), covering many types. Most of them are in the <code>SysUtils</code> unit.\n// They give you a lot of flexibility in formatting.\n** <em>Another advantage</em>: Consistent with the reverse functions. To convert a string (for example, user input) back to an integer or float, you use <code>StrToInt</code>, <code>StrToFloat</code> and friends (like <code>StrToIntDef</code>).\n** <em>Disadvantage</em>: A long concatenation of many <code>XxxToStr</code> calls and strings doesn&#39;t look nice.\n//For classes, they can override the <code>TObject.ToString</code> method.\n//It doesn&#39;t have that clean <em>separation of pattern and arguments</em> property of <code>Format</code> call.</p></li><li><p>The <code>Format</code> function, used like <code>Format(&#39;%d %f %s&#39;, [MyInt, MyFloat, MyString])</code>. This is like <code>sprintf</code> function in the C-like languages. It inserts the arguments into the placeholders in the pattern. The placeholders may use special syntax to influence formatting, e.g. <code>%.4f</code> results in a floating-point format with 4 digits after the decimal point.</p><p>** <em>Advantage</em>: The separation of <em>pattern</em> string from <em>arguments</em> looks clean. If you need to change the pattern string without touching the arguments (e.g. when translating), you can do it easily.\n** <em>Another advantage</em>: No compiler magic. You can use the same syntax to pass any number of arguments of an arbitrary type in your own routines (declare parameter as an <code>array of const</code>). You can then pass these arguments downward to <code>Format</code>, or deconstruct the list of parameters and do anything you like with them.\n** <em>Disadvantage</em>: Compiler does not check whether the pattern matches the arguments. Using a wrong placeholder type will result in an exception at runtime (<code>EConvertError</code> exception, not anything nasty like <em>Access Violation (Segmentation Fault)</em> error).\n//Note that, unlike the C <code>sprintf</code>, the correctness at runtime can be completely verified (there are no dirty pointer tricks inside</p></li><li><p><code>WriteStr(TargetString, ...)</code> routine behaves much like <code>Write(...)</code>, except that the result is saved to the <code>TargetString</code>.</p><p>** <em>Advantage</em>: It supports all the features of <code>Write</code>, including the special syntax for formatting like <code>Pi:1:4</code>.\n** <em>Disadvantage</em>: The special syntax for formatting is a &quot;compiler magic&quot;, implemented specifically for routines like this. This is sometimes troublesome, e.g. you cannot create your own routine <code>MyStringFormatter(...)</code> that would also allow the special syntax like <code>Pi:1:4</code>. For this reason (and also because it wasn&#39;t implemented for a long time in major Pascal compilers), this construction is not very popular.</p></li></ul>\n<h2 id=\"units\">Units</h2>\n<h3 id=\"overview\">Overview</h3>\n<p>Units allow you to group common stuff (anything that can be declared), for usage by other units and programs. They are equivalent to <em>modules</em> and <em>packages</em> in other languages. They have an interface section, where you declare what is available for other units and programs, and then the implementation.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/myunit.pas[]</p>\n<hr />\n<p>A program can use a unit by a <code>uses</code> keyword:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/myunit_test.dpr[]</p>\n<hr />\n<h3 id=\"extensions-used-for-units-and-programs\">Extensions used for units and programs</h3>\n<p>Save the unit file <code>MyUnit</code> as <code>myunit.pas</code>. That is, lowercase with <code>.pas</code> extension.</p>\n<p>[NOTE]\n====\nOther conventions are possible.</p>\n<p>E.g. FPC allows other file extensions for units. And some people use <code>.pp</code> for unit files, like <code>myunit.pp</code>.</p>\n<p>Using a different case is also possible. On Windows file systems, the letter case doesn&#39;t matter. But on Unix file systems is does matter and FPC allows only to use <em>the exact same case as was specified in Pascal <code>uses</code> clause</em> (so <code>MyUnit.pas</code>) or <em>all lowercase</em> (so <code>myunit.pas</code>). Since Pascal is case-insensitive, the first rule sometimes causes issues when people specify unit names with different case in different places.</p>\n<p>All in all, we recommend the simple above rule <em>all lowercase, <code>.pas</code> extension</em> for your projects. This matches the most common established practices and works with all compilers and file systems without issues.\n====</p>\n<p>Save the <code>program</code> to a file with:</p>\n<ul><li><code>.dpr</code> extension (short for <em>&quot;Delphi Project&quot;</em>), if you want the project to be compatible with both <em>FPC/Lazarus</em> and <em>Delphi</em>,</li><li><code>.lpr</code> extension (short for <em>&quot;Lazarus Project&quot;</em>), if you want to use only <em>FPC/Lazarus</em>.</li></ul>\n<p>NOTE: Other conventions are possible and used by some projects. E.g. some projects use <code>.pas</code> for main program file. Some projects use <code>.pp</code> for units or programs. There are reasonable reasons for this (e.g. for FPC programs, that don&#39;t use Lazarus LCL, neither description <em>&quot;Lazarus Project&quot;</em> nor <em>&quot;Delphi Project&quot;</em> are strictly correct)... But for the sake of simplicity, we recommend the above conventions (<code>.dpr</code> or <code>.lpr</code>), as they cover the most common established practices.</p>\n<h3 id=\"initialization-and-finalization\">Initialization and finalization</h3>\n<p>A unit may also contain <code>initialization</code> and <code>finalization</code> sections. This is the code executed when the program starts and ends.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/initialization_finalization.pas[]</p>\n<hr />\n<h3 id=\"units-using-each-other\">Units using each other</h3>\n<p>One unit can also use another unit. Another unit can be used in the interface section, or only in the implementation section. The former allows to define new public stuff (procedures, types...) on top of another unit&#39;s stuff. The latter is more limited (if you use a unit only in the implementation section, you can use its identifiers only in your implementation).</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/anotherunit.pas[]</p>\n<hr />\n<p>It is not allowed to have <em>circular unit dependencies in the interface</em>. That is, two units cannot use each other in the interface section.\n//that everything must be declared before it&#39;s used.\nThe reason is that in order to &quot;understand&quot;\n//(e.g. determine the memory layout of all the structures)\nthe interface section of a unit, the compiler must first &quot;understand&quot; all the units it uses in the interface section. Pascal language follows this rule strictly, and it allows a fast compilation and fully automatic detection on the compiler side <em>what units need to be recompiled</em>. There is no need to use complicated <code>Makefile</code> files for a simple task of compilation in Pascal, and there is no need to <em>recompile everything</em> just to make sure that all dependencies are updated correctly.\n//, but also makes circular dependencies <em>between units interfaces</em> impossible.\n//(That said, this constraint is not existing in some other languages. You can actually do parsing without &quot;complete understanding&quot; of your dependencies, just some stuff will have to be resolved later, e.g. at linking. You can also &quot;repeat&quot; the compilation until your knowledge is &quot;settled&quot;. Anyway, you have to live with this constraint now, and enjoy fast compilation times.:)</p>\n<p>It is <em>OK to make a circular dependency between units when at least one &quot;usage&quot; is only in the implementation</em>. So it&#39;s OK for unit <code>A</code> to use unit <code>B</code> in the interface, and then unit <code>B</code> to use unit <code>A</code> in the implementation.</p>\n<h3 id=\"qualifying-identifiers-with-unit-name\">Qualifying identifiers with unit name</h3>\n<p>Different units may define the same identifier. To keep the code simple to read and search, you should usually avoid it, but it&#39;s not always possible.\n// in some situations (e.g. when you use a third-party library).\nIn such cases, the last unit on the <code>uses</code> clause &quot;wins&quot;, which means that the identifiers it introduces hide the same identifiers introduced by earlier units.</p>\n<p>You can always explicitly define a unit of a given identifier, by using it like <code>MyUnit.MyIdentifier</code>. This is the usual solution when the identifier you want to use from <code>MyUnit</code> is hidden by another unit. Of course you can also rearrange the order of units on your uses clause, although this can affect other declarations than the one you&#39;re trying to fix.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>program showcolor;</p>\n<p>{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}\n{$ifdef MSWINDOWS} {$apptype CONSOLE} {$endif}</p>\n<p>// Both Graphics and GoogleMapsEngine units define TColor type.\nuses Graphics, GoogleMapsEngine;</p>\n<p>var\n  { This doesn&#39;t work like we want, as TColor ends up\n    being defined by GoogleMapsEngine. }\n  // Color: TColor;\n  { This works Ok. }\n  Color: Graphics.TColor;\nbegin\n  Color := clYellow;\n  WriteLn(Red(Color), &#39; &#39;, Green(Color), &#39; &#39;, Blue(Color));\nend.</p>\n<hr />\n<p>In case of units, remember that they have two <code>uses</code> clauses: one in the interface, and another one in the implementation. The rule <em>later units hide the stuff from earlier units</em> is applied here consistently, which means that <em>units used in the implementation section</em> can hide identifiers from units <em>used in the interface section</em>. However, remember that when reading the <code>interface</code> section, only the units used in the interface matter. This may create a confusing situation, where two seemingly-equal declarations are considered different by the compiler:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>unit UnitUsingColors;</p>\n<p>{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}</p>\n<p>// INCORRECT example</p>\n<p>interface</p>\n<p>uses Graphics;</p>\n<p>procedure ShowColor(const Color: TColor);</p>\n<p>implementation</p>\n<p>uses GoogleMapsEngine;</p>\n<p>procedure ShowColor(const Color: TColor);\nbegin\n  // WriteLn(ColorToString(Color));\nend;</p>\n<p>end.</p>\n<hr />\n<p>The unit <code>Graphics</code> (from Lazarus LCL) defines the <code>TColor</code> type. But the compiler will fail to compile the above unit, claiming that you don&#39;t implement a procedure <code>ShowColor</code> that matches the interface declaration. The problem is that unit <code>GoogleMapsEngine</code> also defines a <code>TColor</code> type. And it is used only in the <code>implementation</code> section, therefore it <em>shadows</em> the <code>TColor</code> definition only in the implementation. The equivalent version of the above unit, where the error is obvious, looks like this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>unit UnitUsingColors;</p>\n<p>{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}</p>\n<p>// INCORRECT example.\n// This is what the compiler &quot;sees&quot; when trying to compile previous example</p>\n<p>interface</p>\n<p>uses Graphics;</p>\n<p>procedure ShowColor(const Color: Graphics.TColor);</p>\n<p>implementation</p>\n<p>uses GoogleMapsEngine;</p>\n<p>procedure ShowColor(const Color: GoogleMapsEngine.TColor);\nbegin\n  // WriteLn(ColorToString(Color));\nend;</p>\n<p>end.</p>\n<hr />\n<p>The solution is trivial in this case, just change the implementation to explicitly use <code>TColor</code> from <code>Graphics</code> unit. You could fix it also by moving the <code>GoogleMapsEngine</code> usage, to the interface section and earlier than <code>Graphics</code>, although this could result in other consequences in real-world cases, when <code>UnitUsingColors</code> would define more things.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>unit UnitUsingColors;</p>\n<p>{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}</p>\n<p>interface</p>\n<p>uses Graphics;</p>\n<p>procedure ShowColor(const Color: TColor);</p>\n<p>implementation</p>\n<p>uses GoogleMapsEngine;</p>\n<p>procedure ShowColor(const Color: Graphics.TColor);\nbegin\n  // WriteLn(ColorToString(Color));\nend;</p>\n<p>end.</p>\n<hr />\n<h3 id=\"exposing-one-unit-identifiers-from-another\">Exposing one unit identifiers from another</h3>\n<p>Sometimes you want to take an identifier from one unit, and <em>expose</em> it in a new unit. The end result should be that using the new unit will make the identifier available in the namespace.</p>\n<p>Sometimes this is necessary to preserve backward compatibility with previous unit versions. Sometimes it&#39;s nice to &quot;hide&quot; an internal unit this way.</p>\n<p>This can be done by redefining the identifier in your new unit.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>unit MyUnit;</p>\n<p>{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}</p>\n<p>interface</p>\n<p>uses Graphics;</p>\n<p>type\n  { Expose TColor from Graphics unit as TMyColor. }\n  TMyColor = TColor;</p>\n<p>  { Alternatively, expose it under the same name.\n    Qualify with unit name in this case, otherwise\n    we would refer to ourselves with &quot;TColor = TColor&quot; definition. }\n  TColor = Graphics.TColor;</p>\n<p>const\n  { This works with constants too. }\n  clYellow = Graphics.clYellow;\n  clBlue = Graphics.clBlue;</p>\n<p>implementation</p>\n<p>end.</p>\n<hr />\n<p>Note that this trick cannot be done as easily with global procedures, functions and variables. With procedures and functions, you could expose a constant pointer to a procedure in another unit (see &lt;&lt;Callbacks&gt;&gt;), but that looks quite dirty.</p>\n<p>The usual solution is to create trivial &quot;wrapper&quot; functions that simply call the functions from the internal unit, passing the parameters and return values as needed.</p>\n<p>To make this work with global variables, one can use global (unit-level) properties, see &lt;&lt;Properties&gt;&gt;.</p>\n<h2 id=\"classes\">Classes</h2>\n<h3 id=\"basics-2\">Basics</h3>\n<p>We have classes. At the basic level, a class is just a container for</p>\n<ul><li><em>fields</em> (which is fancy name for <em>&quot;a variable inside a class&quot;</em>),</li><li><em>methods</em> (which is fancy name for <em>&quot;a procedure or function inside a class&quot;</em>),</li><li>and <em>properties</em> (which is a fancy syntax for something that looks like a field, but is in fact a pair of methods to <em>get</em> and <em>set</em> something; more in &lt;&lt;Properties&gt;&gt;).</li><li>Actually, there are more possibilities, described in &lt;&lt;More stuff inside classes and nested classes&gt;&gt;.</li></ul>\n<p>[source,pascal]</p>\n<hr />\n<p>type\n  TMyClass = class\n    MyInt: Integer; // this is a field\n    property MyIntProperty: Integer read MyInt write MyInt; // this is a property\n    procedure MyMethod; // this is a method\n  end;</p>\n<p>procedure TMyClass.MyMethod;\nbegin\n  WriteLn(MyInt + 10);\nend;</p>\n<hr />\n<h3 id=\"inheritance-virtual-methods-override-reintroduce\">Inheritance, virtual methods, override, reintroduce</h3>\n<p>We have inheritance and virtual methods.</p>\n<p>In the example below, class <code>TMyClassDescendant</code> <em>inherits</em> from class <code>TMyClass</code>. The <code>TMyClassDescendant</code> is a <em>descendant</em> of <code>TMyClass</code>, and <code>TMyClass</code> is an <em>ancestor</em> of <code>TMyClassDescendant</code>.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/inheritance.dpr[]</p>\n<hr />\n<p>When a method is <em>virtual</em> it means that the compiler searches for the method implementation at runtime, based on the actual class of the instance. What does this mean in practice?</p>\n<ul><li><p>Run the above example unmodified. Note that the method <code>MyVirtualMethod</code> is virtual. The call <code>C.MyVirtualMethod</code> selects the appropriate implementation based on the actual class of the instance <code>C</code>. When <code>C</code> is of class <code>TMyClassDescendant</code>, the <code>TMyClassDescendant.MyVirtualMethod</code> implementation is called. Thus the output should be:</p><p>+</p></li></ul>\n<pre><code>TMyClass shows MyInt + 10: 10\nTMyClassDescendant shows MyInt + 20: 20</code></pre>\n<ul><li><p>Now modify the above example removing the <code>virtual;</code> and <code>override;</code> pieces. Both calls <code>C.MyVirtualMethod</code> will now call the implementation from <code>TMyClass</code>, because <code>C</code> is declared as <code>TMyClass</code>, so at <em>compile-time</em> all the compiler knows is that <code>C</code> is a <code>TMyClass</code>. The output will be:</p><p>+</p></li></ul>\n<pre><code>TMyClass shows MyInt + 10: 10\nTMyClass shows MyInt + 10: 20</code></pre>\n<p>+\nIn short, this is usually not what you want. You want virtual methods.</p>\n<p>By default methods are not virtual, declare them with <code>virtual</code> to make them so. Overrides must be marked with <code>override</code>, otherwise you will get a warning. To hide a method (declared in ancestor as <code>virtual</code>) without overriding it (usually you don&#39;t want to do this, unless you know what you&#39;re doing) use <code>reintroduce</code>.</p>\n<h3 id=\"classes-and-class-instances-constructors-destructors\">Classes and class instances, constructors, destructors</h3>\n<p>Example in the section above shows a <em>class</em> called <code>TMyClass</code> (and another class called <code>TMyClassDescendant</code>). The <em>class</em> is a <em>type</em>, you can also think of it as a <em>template</em>. The class itself doesn&#39;t hold any values -- there is no memory reserved for the field <code>MyInt: Integer</code> declared in the example above.</p>\n<p>NOTE: It is actually possible for a class to <em>&quot;hold values&quot;</em> by using <em>class variables</em>, but for now let&#39;s forget about this possibility. Focus on simple classes that have only regular fields.</p>\n<p>To reserve memory for the fields, we need to create a <em>class instance</em>.</p>\n<p>Creating the class instance is done by invoking a <em>constructor</em>.</p>\n<ul><li>Constructor is a special kind of a method, using the keyword <code>constructor</code>.</li><li>Before invoking a constructor, a memory for the class instance is allocated, and then the constructor code is called.</li><li>You don&#39;t need to define a constructor in all your classes. All classes implicitly descend from the <code>TObject</code> which has a parameter-less constructor called <code>Create</code>. So you always have a constructor, even if you didn&#39;t define one.</li><li>But you <em>can</em> define a constructor in your class. It&#39;s the best way to initialize a class instance. If you want to later depend that e.g. &quot;initial value of field X is Y&quot;, then make it so (<code>X := Y;</code>) in the constructor.</li><li>Your own constructors are usually also called just <code>Create</code>. More details about naming constructors and destructors are in &lt;&lt;The virtual destructor called Destroy&gt;&gt;.</li></ul>\n<p>You invoke the constructor, allocating a class instance, like this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>X := TMyClass.Create;</p>\n<hr />\n<p>You define your own constructor like this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>type\n  TMyClass = class\n  public\n    X: Integer;\n    constructor Create;\n  end;</p>\n<p>constructor TMyClass.Create;\nbegin\n  inherited Create; // Call the ancestor constructor\n  // Initialization code here\n  X := 123;\nend;</p>\n<hr />\n<p>Conversely, when a class is <em>destroyed</em>, a <code>destructor</code> is called.</p>\n<ul><li>It is again a special kind of a method, using the keyword <code>destructor</code>.</li><li>After invoking the destructor, a memory for the class instance is released. Accessing the fields of the destroyed instance is no longer allowed.</li><li>Again, you don&#39;t need to define a destructor in all your classes. All classes implicitly descend from the <code>TObject</code> which has a parameter-less destructor called <code>Destroy</code>.</li><li>But you <em>can</em> define a destructor in your class. This is your last chance to do any &quot;cleanup&quot;. E.g. maybe your class instance created some other class instances, internal, and now they need to be freed.</li><li>If you define one, there should be only one destructor, called <code>Destroy</code>, always with <code>override;</code>. More details why it should be so are in &lt;&lt;The virtual destructor called Destroy&gt;&gt;.</li></ul>\n<p>Here&#39;s an example:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/constructor_destructor.dpr[]</p>\n<hr />\n<h3 id=\"testing-class-is-typecasting-as-tmyclass-x\">Testing class (is), typecasting (as, TMyClass(X))</h3>\n<p>To test the class of an instance at runtime, use the <code>is</code> operator. To typecast the instance to a specific class, use the <code>as</code> operator.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/is_as.dpr[]</p>\n<hr />\n<p>Instead of casting using <code>X as TMyClass</code>, you can also use the <em>unchecked</em> typecast <code>TMyClass(X)</code>. This is faster, but results in an undefined behavior if the <code>X</code> is not, in fact, a <code>TMyClass</code> descendant. So don&#39;t use the <code>TMyClass(X)</code> typecast, or use it only in a code where it&#39;s blindingly obvious that it&#39;s correct, for example right after testing with <code>is</code>:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>if A is TMyClass then\n  (A as TMyClass).CallSomeMethodOfMyClass;\n// below is marginally faster\nif A is TMyClass then\n  TMyClass(A).CallSomeMethodOfMyClass;</p>\n<hr />\n<h3 id=\"properties\">Properties</h3>\n<p>Properties are a very nice <em>&quot;syntactic sugar&quot;</em> to</p>\n<ol><li>Make something that looks like a field (can be read and set) but underneath is realized by calling a <em>getter</em> and <em>setter</em> methods. The typical usage is to perform some side-effect (e.g. redraw the screen) each time some value changes.</li><li>Make something that looks like a field, but is read-only. In effect, it&#39;s like a constant or a parameter-less function.</li></ol>\n<p>[source,pascal]</p>\n<hr />\n<p>type\n  TWebPage = class\n  private\n    FURL: string;\n    FColor: TColor;\n    function SetColor(const Value: TColor);\n  public\n    { No way to set it directly.\n      Call the Load method, like Load(&#39;<a href=\"http://www.freepascal.org/\" rel=\"nofollow ugc noopener\">http://www.freepascal.org/</a>&#39;),\n      to load a page and set this property. }\n    property URL: string read FURL;\n    procedure Load(const AnURL: string);\n    property Color: TColor read FColor write SetColor;\n  end;</p>\n<p>procedure TWebPage.Load(const AnURL: string);\nbegin\n  FURL := AnURL;\n  NetworkingComponent.LoadWebPage(AnURL);\nend;</p>\n<p>function TWebPage.SetColor(const Value: TColor);\nbegin\n  if FColor &lt;&gt; Value then\n  begin\n    FColor := Value;\n    // for example, cause some update each time value changes\n    Repaint;\n    // as another example, make sure that some underlying instance,\n    // like a &quot;RenderingComponent&quot; (whatever that is),\n    // has a synchronized value of Color.\n    RenderingComponent.Color := Value;\n  end;\nend;</p>\n<hr />\n<p>// { compare with the old value, to shield from making\n//   useless assignments to RenderingComponent.Color.\n//   This is a common approach to guarantee that setting WebPage.Color\n//   many times to the same value will be fast,\n//   even if setting RenderingComponent.Color many times to the same value\n//   would be slow. }</p>\n<p>Note that instead of specifying a method, you can also specify a field (typically a private field) to directly get or set. In the example above, the <code>Color</code> property uses a <em>setter</em> method <code>SetColor</code>. But for getting the value, the <code>Color</code> property refers directly to the private field <code>FColor</code>. Directly referring to a field is faster than implementing trivial getter or setter methods (faster for you, and faster at execution).</p>\n<p>When declaring a property you specify:</p>\n<p>. Whether it can be read, and how (by directly reading a field, or by using a &quot;getter&quot; method).\n. And, in a similar manner, whether it can be set, and how (by directly writing to a designated field, or by calling a &quot;setter&quot; method).</p>\n<p>The compiler checks that the types and parameters of indicated fields and methods match with the property type. For example, to read an <code>Integer</code> property you have to either provide an <code>Integer</code> field, or a parameter-less method that returns an <code>Integer</code>.</p>\n<p>Technically, for the compiler, the &quot;getter&quot; and &quot;setter&quot; methods are just normal methods and they can do absolutely anything (including side-effects or randomization). But it&#39;s a good convention to design properties to behave more-or-less like fields:</p>\n<p>// There are some good conventions to follow when creating properties. These are only conventions, the compiler doesn&#39;t prevent you from making something weird using properties -- f. But the good\n// They should be somewhat predictable, like fields:</p>\n<ul><li><p>The <em>getter</em> function should have no visible side-effects (e.g. it should not read some input from file / keyboard). It should be deterministic (no randomization, not even pseudo-randomization :). Reading a property many times should be valid, and return the same value, if nothing changed in-between.</p><p>+\nNote that it&#39;s OK for <em>getter</em> to have some <em>invisible</em> side-effect, for example to cache a value of some calculation (known to produce the same results for given instance), to return it faster next time. This is in fact one of the cool possibilities of a &quot;getter&quot; function.</p></li><li>The <em>setter</em> function should always set the requested value, such that calling the <em>getter</em> yields it back. Do not reject invalid values silently in the &quot;setter&quot; (raise an exception if you must). Do not convert or scale the requested value. The idea is that after <code>MyClass.MyProperty := 123;</code> the programmer can expect that <code>MyClass.MyProperty = 123</code>.</li><li>The <em>read-only properties</em> are often used to make some field read-only from the outside. Again, the good convention is to make it behave like a constant, at least constant for this object instance with this state. The value of the property should not change unexpectedly. <em>Make it a function, not a property, if using it has a side effect or returns something random.</em></li><li>The <em>&quot;backing&quot; field of a property is almost always private</em>, since the idea of a property is to encapsulate all outside access to it.</li><li>It&#39;s technically possible to make <em>set-only properties</em>, but I have not yet seen a good example of such thing:)</li></ul>\n<p>NOTE: Properties can also be defined outside of class, at a unit level. They serve an analogous purpose then: look like a global variable, but are backed by a <em>getter</em> and <em>setter</em> routines.</p>\n<h4 id=\"serialization-of-properties\">Serialization of properties</h4>\n<p><em>Published properties</em> are the basis of a <em>serialization</em> (also known as <em>streaming components</em>) in Pascal. <em>Serialization</em> means that the instance data is recorded into a stream (like a file), from which it can be later restored.</p>\n<p>Serialization is what happens when Lazarus reads (or writes) the component state from an <code>xxx.lfm</code> file. (In Delphi, the equivalent file has <code>.dfm</code> extension.) You can also use this mechanism explicitly, using routines like <code>ReadComponentFromTextStream</code> from the <code>LResources</code> unit. You can also use other serialization algorithms, e.g. <code>FpJsonRtti</code> unit (serializing to JSON).</p>\n<p><em>In the Castle Game Engine:</em> Use the <code>CastleComponentSerialize</code> unit (based on <code>FpJsonRtti</code>) to serialize our user-interface and transformation component hierarchies.</p>\n<p>At each property, you can declare some additional things that will be helpful for any serialization algorithm:</p>\n<ul><li>You can specify the property default value (using the <code>default</code> keyword). Note that you are still required to initialize the property in the constructor to this exact default value (it is not done automatically). The <code>default</code> declaration is merely an information to the serialization algorithm: <em>&quot;when the constructor finishes, the given property has the given value&quot;</em>.</li><li>Whether the property should be stored at all (using the <code>stored</code> keyword).</li></ul>\n<h3 id=\"exceptions-quick-example\">Exceptions - Quick Example</h3>\n<p>We have exceptions. They can be caught with <code>try ... except ... end</code> clauses, and we have <code>finally</code> sections like <code>try ... finally ... end</code>.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/exception_finally.dpr[]</p>\n<hr />\n<p>Note that the <code>finally</code> clause is executed even if you exit the block using the <code>Exit</code> (from function / procedure / method) or <code>Break</code> or <code>Continue</code> (from loop body).</p>\n<p>See the &lt;&lt;Exceptions&gt;&gt; chapter for more in-depth description of <em>exceptions</em>.</p>\n<h3 id=\"visibility-specifiers\">Visibility specifiers</h3>\n<p>As in most object-oriented languages, we have visibility specifiers to hide fields / methods / properties.</p>\n<p>The basic visibility levels are:</p>\n<p><code>public</code>:: everyone can access it, including the code in other units.\n<code>private</code>:: only accessible in this class.\n<code>protected</code>:: only accessible in this class and descendants.</p>\n<p>The explanation of <code>private</code> and <code>protected</code> visibility above is not precisely true. The code <em>in the same unit</em> can overcome their limits, and access the <code>private</code> and <code>protected</code> stuff freely. Sometimes this is a nice feature, allows you to implement tightly-connected classes. Use <code>strict private</code> or <code>strict protected</code> to secure your classes more tightly. See the &lt;&lt;Private and strict private&gt;&gt;.</p>\n<p>By default, if you don&#39;t specify the visibility, then the visibility of declared stuff is <code>public</code>. The exception is for classes compiled with <code>{$M+}</code>, or descendants of classes compiled with <code>{$M+}</code>, which includes all descendants of <code>TPersistent</code>, which also includes all descendants of <code>TComponent</code> (since <code>TComponent</code> descends from <code>TPersistent</code>). For them, the default visibility specifier is <code>published</code>, which is like <code>public</code>, but in addition the streaming system knows to handle this.</p>\n<p>Not every field and property type is allowed in the <code>published</code> section (not every type can be streamed, and only classes can be streamed from simple fields). Just use <code>public</code> if you don&#39;t care about streaming but want something available to all users.</p>\n<h3 id=\"default-ancestor\">Default ancestor</h3>\n<p>If you don&#39;t declare the ancestor type, every <code>class</code> inherits from <code>TObject</code>.</p>\n<h3 id=\"self\">Self</h3>\n<p>The special keyword <code>Self</code> can be used within the class implementation to explicitly refer to your own instance. It is equivalent to <code>this</code> from C++, Java and similar languages.</p>\n<h3 id=\"calling-inherited-method\">Calling inherited method</h3>\n<p>Within a method implementation, if you call another method, then by default you call the method of your own class. In the example code below, <code>TMyClass2.MyOtherMethod</code> calls <code>MyMethod</code>, which ends up calling <code>TMyClass2.MyMethod</code>.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/method_calls_inheritance_1.dpr[]</p>\n<hr />\n<p>If the method is not defined in a given class, then it calls the method of an ancestor class. In effect, when you call <code>MyMethod</code> on an instance of <code>TMyClass2</code>, then</p>\n<ul><li>The compiler looks for <code>TMyClass2.MyMethod</code>.</li><li>If not found, it looks for <code>TMyClass1.MyMethod</code>.</li><li>If not found, it looks for <code>TObject.MyMethod</code>.</li><li>if not found, then the compilation fails.</li></ul>\n<p>You can test it by commenting out the <code>TMyClass2.MyMethod</code> definition in the example above. In effect, <code>TMyClass1.MyMethod</code> will be called by <code>TMyClass2.MyOtherMethod</code>.</p>\n<p>Sometimes, you don&#39;t want to call the method of your own class. You want to call the method of an ancestor (or ancestor&#39;s ancestor, and so on). To do this, add the keyword <code>inherited</code> before the call to <code>MyMethod</code>, like this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>inherited MyMethod;</p>\n<hr />\n<p>This way you <em>force</em> the compiler to start searching from an ancestor class. In our example, it means that compiler is searching for <code>MyMethod</code> inside <code>TMyClass1.MyMethod</code>, then <code>TObject.MyMethod</code>, and then gives up. It does not even consider using the implementation of <code>TMyClass2.MyMethod</code>.</p>\n<p>TIP: Go ahead, change the implementation of <code>TMyClass2.MyOtherMethod</code> above to use <code>inherited MyMethod</code>, and see the difference in the output.</p>\n<p>The <code>inherited</code> call is often used to call the ancestor method of the same name. This way the descendants can enhance the ancestors (keeping the ancestor functionality, instead of replacing the ancestor functionality). Like in the example below.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/method_calls_inherited.dpr[]</p>\n<hr />\n<p>Since using <code>inherited</code> to call a method with the same name, with the same arguments, is a very common case, there is a special shortcut for it: you can just write <code>inherited;</code> (<code>inherited</code> keyword followed immediately by a semicolon, instead of a method name). This means &quot;<em>call an inherited method with the same name, passing it the same arguments as the current method</em>&quot;.</p>\n<p>TIP: In the above example, all the <code>inherited ...;</code> calls could be replaced by a simple <code>inherited;</code>.</p>\n<p>Note 1: The <code>inherited;</code> is really just a shortcut for calling the ancestor&#39;s method with the <em>same variables passed in</em>. If you have modified your own parameter (which is possible, if the parameter is not <code>const</code>), then the ancestor&#39;s method can receive different input values from your descendant. Consider this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>procedure TMyClass2.MyMethod(A: Integer);\nbegin\n  WriteLn(&#39;TMyClass2.MyMethod beginning &#39;, A);\n  A := 456;\n  { This calls TMyClass1.MyMethod with A = 456,\n    regardless of the A value passed to this method (TMyClass2.MyMethod). }\n  inherited;\n  WriteLn(&#39;TMyClass2.MyMethod ending &#39;, A);\nend;</p>\n<hr />\n<p>Note 2: You usually want to make the <code>MyMethod</code> <em>virtual</em> when many classes (along the &quot;<em>inheritance chain</em>&quot;) define it. More about the virtual methods in the section below. But the <code>inherited</code> keyword works regardless of whether the method is virtual or not. The <code>inherited</code> always means that the compiler starts searching for the method in an ancestor, and it makes sense for both <em>virtual</em> and <em>non-virtual</em> methods.</p>\n<h3 id=\"virtual-methods-override-and-reintroduce\">Virtual methods, override and reintroduce</h3>\n<p>By default, the methods are <em>not virtual</em>. This is similar to C++, and unlike Java.</p>\n<p>When a method is <em>not virtual</em>, the compiler determines which method to call based on the currently <em>declared</em> class type, not based on the <em>actually created</em> class type. The difference seems subtle, but it&#39;s important when your variable is declared to have a class like <code>TFruit</code>, but it may be in fact a descendant class like <code>TApple</code>.</p>\n<p>The idea of the object-oriented programming is that <em>the descendant class is always as good as the ancestor</em>, so the compiler allows to use a descendant class always when the ancestor is expected. When your method is not virtual, this can have undesired consequences. Consider the example below:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/without_virtual_methods.dpr[]</p>\n<hr />\n<p>This example will print</p>\n<hr />\n<p>We have a fruit with class TApple\nWe eat it:\nEating a fruit</p>\n<hr />\n<p>In effect, the call <code>Fruit.Eat</code> called the <code>TFruit.Eat</code> implementation, and nothing calls the <code>TApple.Eat</code> implementation.</p>\n<p>If you think about how the compiler works, this is natural: when you wrote the <code>Fruit.Eat</code>, the <code>Fruit</code> variable was declared to hold a class <code>TFruit</code>. So the compiler was searching for the method called <code>Eat</code> within the <code>TFruit</code> class. If the <code>TFruit</code> class would not contain such method, the compiler would search within an ancestor (<code>TObject</code> in this case). But the compiler <em>cannot search within descendants (like <code>TApple</code>)</em>, as it doesn&#39;t know whether the <em>actual class</em> of <code>Fruit</code> is <code>TApple</code>, <code>TFruit</code>, or some other <code>TFruit</code> descendant (like a <code>TOrange</code>, not shown in the example above).</p>\n<p>In other words, the <em>method to be called</em> is determined <em>at compile-time</em>.</p>\n<p>Using the <em>virtual methods</em> changes this behavior. <em>If the <code>Eat</code> method would be virtual</em> (an example of it is shown below), then the actual implementation to be called is determined <em>at runtime</em>. If the <code>Fruit</code> variable will hold an instance of the class <code>TApple</code> (even if it&#39;s declared as <code>TFruit</code>), then the <code>Eat</code> method will be searched within the <code>TApple</code> class first.</p>\n<p>In Object Pascal, to define a method as <em>virtual</em>, you need to</p>\n<ul><li>Mark its first definition (in the top-most ancestor) with the <code>virtual</code> keyword.</li><li>Mark all the other definitions (in the descendants) with the <code>override</code> keyword. All the overridden versions must have exactly the same parameters (and return the same types, in case of functions).</li></ul>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/with_virtual_methods.dpr[]</p>\n<hr />\n<p>This example will print</p>\n<hr />\n<p>We have a fruit with class TApple\nWe eat it:\nEating an apple</p>\n<hr />\n<p>Internally, virtual methods work by having so-called <em>virtual method table</em> associated with each class. This table is a list of pointers to the implementations of virtual methods for this class. When calling the <code>Eat</code> method, the compiler looks into a virtual method table associated with the actual class of <code>Fruit</code>, and uses a pointer to the <code>Eat</code> implementation stored there.</p>\n<p>If you don&#39;t use the <code>override</code> keyword, the compiler will warn you that you&#39;re <em>hiding</em> (obscuring) the virtual method of an ancestor with a non-virtual definition. If you&#39;re sure that this is what you want, you can add a <code>reintroduce</code> keyword. But in most cases, you will rather want to keep the method virtual, and add the <code>override</code> keyword, thus making sure that it&#39;s always invoked correctly.</p>\n<h2 id=\"freeing-classes\">Freeing classes</h2>\n<h3 id=\"remember-to-free-the-class-instances\">Remember to free the class instances</h3>\n<p>The class instances have to be manually freed, otherwise you get memory leaks.</p>\n<p>We advise to automatically detect memory leaks using:</p>\n<ul><li>FPC command-line options <code>-gl -gh</code></li><li>Delphi <code>ReportMemoryLeaksOnShutdown := true</code></li><li>Castle Game Engine <code>detect_memory_leaks=&quot;true&quot;</code> in <code>CastleEngineManifest.xml</code></li></ul>\n<p>See <a href=\"https://castle-engine.io/memory_leaks\" rel=\"nofollow ugc noopener\">https://castle-engine.io/memory_leaks</a> for more information.</p>\n<p>NOTE: You don&#39;t need to free the instances of raised exceptions. Although you do create an instance when raising an exception (and it&#39;s a perfectly normal class instance). But this class instance is freed automatically.</p>\n<h3 id=\"how-to-free\">How to free</h3>\n<p>To free the class instance, it&#39;s best to call <code>FreeAndNil(A)</code> from <code>SysUtils</code> unit on your class instance. It checks whether <code>A</code> is <code>nil</code>, if not -- calls its destructor, and sets <code>A</code> to <code>nil</code>. So calling it many times in a row is not an error.</p>\n<p>It is more-or-less a shortcut for</p>\n<p>[source,pascal]</p>\n<hr />\n<p>if A &lt;&gt; nil then\nbegin\n  A.Destroy;\n  A := nil;\nend;</p>\n<hr />\n<p>Actually, that&#39;s an oversimplification, as <code>FreeAndNil</code> does a useful trick and sets the variable <code>A</code> to <code>nil</code> <em>before</em> calling the destructor on a suitable reference. This helps to prevent a certain class of bugs -- the idea is that the &quot;outside&quot; code should never access a half-destructed instance of the class.</p>\n<p>Often you will also see people using the <code>A.Free</code> method, which is like doing</p>\n<p>[source,pascal]</p>\n<hr />\n<p>if A &lt;&gt; nil then\n  A.Destroy;</p>\n<hr />\n<p>This frees the <code>A</code>, unless it&#39;s <code>nil</code>.</p>\n<p>Note that in normal circumstances, you should never call a method on an instance which may be <code>nil</code>. So the call <code>A.Free</code> may look suspicious at the first sight, if <code>A</code> can be <code>nil</code>. However, the <code>Free</code> method is an exception to this rule. It does something dirty in the implementation -- namely, checks whether <code>Self &lt;&gt; nil</code>.</p>\n<p>[NOTE]\n====\nThis trick (officially allowing the method to be used with <code>Self</code> equal <code>nil</code>) is possible only in non-virtual methods.</p>\n<p>In the implementation of such method, as long as <code>Self = nil</code> is possible, the method cannot call any virtual methods or access any fields, as these would cause <em>Access Violation (Segmentation Fault)</em> error when called on a <code>nil</code> instance. See the sample code <a href=\"https://github.com/modern-pascal/modern-pascal-introduction/blob/master/code-samples/method_with_self_nil.dpr[method_with_self_nil.dpr]\" rel=\"nofollow ugc noopener\">https://github.com/modern-pascal/modern-pascal-introduction/blob/master/code-samples/method_with_self_nil.dpr[method_with_self_nil.dpr]</a>.</p>\n<p>We discourage from using this trick in your own code (for virtual or non-virtual methods) as it is counter-intuitive to normal usage. In general all instance methods should be able to assume that they work on valid (non-nil) instance and can access fields and call any other methods (virtual or not).\n====</p>\n<p>We advise using <code>FreeAndNil(A)</code> always, without exceptions, and never to call directly the <code>Free</code> method or <code>Destroy</code> destructor.</p>\n<p>The <em>Castle Game Engine</em> does it like that. It helps to keep a nice assertion that <em>all references are either nil, or point to valid instances</em>. Though note that using <code>FreeAndNil(A)</code>  doesn&#39;t <em>guarantee</em> this assertion, it only helps with this. For example, if you copy the instance reference, and call <code>FreeAndNil(A)</code> on one copy, the other copy will be a non-nil dangling pointer.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>A := TMyClass.Create;\nB := A;\nFreeAndNil(A);\n// B now contains a dangling pointer</p>\n<hr />\n<p>More about dealing with this in the later section about <em>&quot;Free notification&quot;</em>.</p>\n<p>Still, <code>FreeAndNil(A)</code> takes care of the most trivial cases, so it&#39;s a good habit to use it IMHO. You will appreciate it when debugging some errors, it is nice to easily observe <em>&quot;<code>X</code> is already freed, because <code>X</code> is <code>nil</code> now&quot;</em>.</p>\n<h3 id=\"manual-and-automatic-freeing\">Manual and automatic freeing</h3>\n<p>In many situations, the need to free the instance is not much problem. You just write a destructor, that matches a constructor, and deallocates everything that was allocated in the constructor (or, more completely, in the whole lifetime of the class). Be careful to only free each thing <em>once</em>. Usually it&#39;s a good idea to set the freed reference to <code>nil</code>, usually it&#39;s most comfortable to do it by calling the <code>FreeAndNil(A)</code>.</p>\n<p>So, like this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>uses SysUtils;</p>\n<p>type\n  TGun = class\n  end;</p>\n<p>  TPlayer = class\n    Gun1, Gun2: TGun;\n    constructor Create;\n    destructor Destroy; override;\n  end;</p>\n<p>constructor TPlayer.Create;\nbegin\n  inherited;\n  Gun1 := TGun.Create;\n  Gun2 := TGun.Create;\nend;</p>\n<p>destructor TPlayer.Destroy;\nbegin\n  FreeAndNil(Gun1);\n  FreeAndNil(Gun2);\n  inherited;\nend;</p>\n<hr />\n<p>To avoid the need to explicitly free the instance, one can also use the <code>TComponent</code> feature of <em>&quot;ownership&quot;</em>. An object that is <em>owned</em> will be automatically freed by the <em>owner</em>. The mechanism is smart and it will never free an already freed instance (so things will also work correctly if you manually free the owned object earlier). We can change the previous example to this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>uses SysUtils, Classes;</p>\n<p>type\n  TGun = class(TComponent)\n  end;</p>\n<p>  TPlayer = class(TComponent)\n    Gun1, Gun2: TGun;\n    constructor Create(AOwner: TComponent); override;\n  end;</p>\n<p>constructor TPlayer.Create(AOwner: TComponent);\nbegin\n  inherited;\n  Gun1 := TGun.Create(Self);\n  Gun2 := TGun.Create(Self);\nend;</p>\n<hr />\n<p>Note that we need to override a virtual <code>TComponent</code> constructor here. So we cannot change the constructor parameters. (Actually, you can -- declare a new constructor with <code>reintroduce</code>. But be careful, as some functionality, e.g. streaming, will still use the virtual constructor, so make sure it works right in either case.)</p>\n<p>Note that you can always use <code>nil</code> value for the owner. This way the <em>&quot;ownership&quot;</em> mechanism will not be used for this component. It makes sense if you need to use the <code>TComponent</code> descendant, but you want to always manually free it. To do this, you would create a component descendant like this: <code>ManualGun := TGun.Create(nil);</code>.</p>\n<p>Another mechanism for automatic freeing is the <code>OwnsObjects</code> functionality (by default already <code>true</code>!) of list-classes like <code>TFPGObjectList</code> or <code>TObjectList</code>. So we can also write:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>uses SysUtils, Classes, FGL;</p>\n<p>type\n  TGun = class\n  end;</p>\n<p>  TGunList = {$ifdef FPC}specialize{$endif} TFPGObjectList&lt;TGun&gt;;</p>\n<p>  TPlayer = class\n    Guns: TGunList;\n    Gun1, Gun2: TGun;\n    constructor Create;\n    destructor Destroy; override;\n  end;</p>\n<p>constructor TPlayer.Create;\nbegin\n  inherited;\n  // Actually, the parameter true (OwnsObjects) is already the default\n  Guns := TGunList.Create(true);\n  Gun1 := TGun.Create;\n  Guns.Add(Gun1);\n  Gun2 := TGun.Create;\n  Guns.Add(Gun2);\nend;</p>\n<p>destructor TPlayer.Destroy;\nbegin\n  { We have to take care to free the list.\n    It will automatically free its contents. }\n  FreeAndNil(Guns);</p>\n<p>  { No need to free the Gun1, Gun2 anymore. It&#39;s a nice habit to set to &quot;nil&quot;\n    their references now, as we know they are freed. In this simple class,\n    with so simple destructor, it&#39;s obvious that they cannot be accessed\n    anymore -- but doing this pays off in case of larger and more complicated\n    destructors.</p>\n<pre><code>Alternatively, we could avoid declaring Gun1 and Gun2,\nand instead use Guns[0] and Guns[1] in own code.\nOr create a method like Gun1 that returns Guns[0]. }</code></pre>\n<p>  Gun1 := nil;\n  Gun2 := nil;\n  inherited;\nend;</p>\n<hr />\n<p>Beware that the list classes &quot;ownership&quot; mechanism is simple, and you will get an error if you free the instance using some other means, while it&#39;s also contained within a list. Use the <code>Extract</code> method to remove something from a list without freeing it, thus taking the responsibility to free it yourself.</p>\n<p><em>In the Castle Game Engine</em>: The descendants of <code>TX3DNode</code> have automatic memory management when inserted as children of another <code>TX3DNode</code>. The root X3D node, <code>TX3DRootNode</code>, is in turn usually owned by <code>TCastleSceneCore</code>. Some other things also have a simple ownership mechanism -- look for parameters and properties called <code>OwnsXxx</code>.</p>\n<h3 id=\"the-virtual-destructor-called-destroy\">The virtual destructor called Destroy</h3>\n<p>As you saw in the examples above, when the class is destroyed, its <code>destructor</code> called <code>Destroy</code> is called.</p>\n<p>In theory, you could have multiple destructors, but in practice it&#39;s almost never a good idea. It&#39;s much easier to have only one destructor called <code>Destroy</code>, which is in turn called by the <code>Free</code> method, which is in turn called by the <code>FreeAndNil</code> procedure.</p>\n<p>The <code>Destroy</code> destructor in the <code>TObject</code> is defined as a <em>virtual</em> method, so you should always mark it with the <code>override</code> keyword in all your classes (since all classes descend from <code>TObject</code>). This makes the <code>Free</code> method work correctly. Recall how the virtual methods work from the &lt;&lt;virtual-methods-section&gt;&gt;.</p>\n<p>[NOTE]\n====\nThis information about <em>destructors</em> is, indeed, inconsistent with the <em>constructors</em>.</p>\n<p>It&#39;s normal that a class has multiple constructors. Usually they are all called <code>Create</code>, and only have different parameters, but it&#39;s also OK to invent other names for constructors.</p>\n<p>Also, the <code>Create</code> constructor in the <code>TObject</code> is <em>not virtual</em>, so you do not mark it with <code>override</code> in the descendants.</p>\n<p>This all gives you a bit of extra flexibility when defining constructors. It is often not necessary to make them virtual, so by default you&#39;re not forced to do it.</p>\n<p>Note, however, that this changes for <code>TComponent</code> descendants. The <code>TComponent</code> defines a virtual constructor <code>Create(AOwner: TComponent)</code>. It needs a virtual constructor in order for the streaming system to work. When defining descendants of the <code>TComponent</code>, you should override this constructor (and mark it with the <code>override</code> keyword), and perform all your initialization inside it. It is still OK to define additional constructors, but they should only act as <em>&quot;helpers&quot;</em>. The instance should always work when created using the <code>Create(AOwner: TComponent)</code> constructor, otherwise it will not be correctly constructed when streaming. The <em>streaming</em> is used e.g. when saving and loading this component on a Lazarus form.\n====</p>\n<h3 id=\"free-notification\">Free notification</h3>\n<p>If you copy a reference to the instance, such that you have two references to the same memory, and then one of them is freed -- the other one becomes a <em>&quot;dangling pointer&quot;</em>. It should not be accessed, as it points to a memory that is no longer allocated. Accessing it may result in a runtime error, or garbage being returned (as the memory may be reused for other stuff in your program).</p>\n<p>Using the <code>FreeAndNil</code> to free the instance doesn&#39;t help here. <code>FreeAndNil</code> sets to <code>nil</code> only the reference it got -- there&#39;s no way for it to set all other references automatically. Consider this code:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>var\n  Obj1, Obj2: TObject;\nbegin\n  Obj1 := TObject.Create;\n  Obj2 := Obj1;\n  FreeAndNil(Obj1);</p>\n<p>  // what happens if we access Obj1 or Obj2 here?\nend;</p>\n<hr />\n<ol><li><p>At the end of this block, the <code>Obj1</code> is <code>nil</code>. If some code has to access it, it can reliably use <code>if Obj1 &lt;&gt; nil then ...</code> to avoid calling methods on a freed instance, like</p><p>+\n[source,pascal]</p></li></ol>\n<hr />\n<p>if Obj1 &lt;&gt; nil then\n  WriteLn(Obj1.ClassName);</p>\n<hr />\n<p>+\nTrying to access a field of a <code>nil</code> instance results in a predictable exception at runtime. So even if some code will not check <code>Obj1 &lt;&gt; nil</code>, and will blindly access <code>Obj1</code> field, you will get a clear exception at runtime.\n+\nSame goes for calling a virtual method, or calling a non-virtual method that accessed a field of a <code>nil</code> instance.</p>\n<ol start=\"2\"><li><p>With <code>Obj2</code>, things are less predictable. It&#39;s not <code>nil</code>, but it&#39;s invalid. Trying to access a field of a non-nil invalid instance</p><p>//(or call a method that accessed a field of such instance)\nresults in an unpredictable behavior -- maybe an access violation exception, maybe a garbage data returned.</p></li></ol>\n<p>There are various solutions to it:</p>\n<ul><li>One solution is to, well, be careful and read the documentation. Don&#39;t assume anything about the lifetime of the reference, if it&#39;s created by other code. If a class <code>TCar</code> has a field pointing to some instance of <code>TWheel</code>, it&#39;s a <em>convention</em> that the reference to <em>wheel</em> is valid as long as the reference to <em>car</em> exists, and the <em>car</em> will free its <em>wheels</em> inside its destructor. But that&#39;s just a convention, the documentation should mention if there&#39;s something more complicated going on.</li><li>In the above example, right after freeing the <code>Obj1</code> instance, you can simply set the <code>Obj2</code> variable explicitly to <code>nil</code>. That&#39;s trivial in this simple case.</li><li><p>The most future-proof solution is to use <code>TComponent</code> class &quot;free notification&quot; mechanism. One component can be notified when another component is freed, and thus set its reference to <code>nil</code>.</p><p>+\nThus you get something like a <em>weak reference</em>. It can cope with various usage scenarios, for example you can allow the code from outside of the class to set your reference, and the outside code can also free the instance at any time.\n+\nThis requires both classes to descend from <code>TComponent</code>. Using it in general boils down to calling <code>FreeNotification</code> , <code>RemoveFreeNotification</code>, and overriding <code>Notification</code>.\n+\nHere&#39;s a complete example, showing how to use this mechanism, together with constructor / destructor and a setter property. Sometimes it can be done simpler, but this is the full-blown version that is always correct:)\n+\n[source,pascal]</p></li></ul>\n<hr />\n<p>type\n  TControl = class(TComponent)\n  end;</p>\n<p>  TContainer = class(TComponent)\n  private\n    FSomeSpecialControl: TControl;\n    procedure SetSomeSpecialControl(const Value: TControl);\n  protected\n    procedure Notification(AComponent: TComponent; Operation: TOperation); override;\n  public\n    destructor Destroy; override;\n    property SomeSpecialControl: TControl\n      read FSomeSpecialControl write SetSomeSpecialControl;\n  end;</p>\n<p>implementation</p>\n<p>procedure TContainer.Notification(AComponent: TComponent; Operation: TOperation);\nbegin\n  inherited;\n  if (Operation = opRemove) and (AComponent = FSomeSpecialControl) then\n    { set to nil by SetSomeSpecialControl to clean nicely }\n    SomeSpecialControl := nil;\nend;</p>\n<p>procedure TContainer.SetSomeSpecialControl(const Value: TControl);\nbegin\n  if FSomeSpecialControl &lt;&gt; Value then\n  begin\n    if FSomeSpecialControl &lt;&gt; nil then\n      FSomeSpecialControl.RemoveFreeNotification(Self);\n    FSomeSpecialControl := Value;\n    if FSomeSpecialControl &lt;&gt; nil then\n      FSomeSpecialControl.FreeNotification(Self);\n  end;\nend;</p>\n<p>destructor TContainer.Destroy;\nbegin\n  { set to nil by SetSomeSpecialControl, to detach free notification }\n  SomeSpecialControl := nil;\n  inherited;\nend;</p>\n<hr />\n<h3 id=\"free-notification-observer-castle-game-engine\">Free notification observer (Castle Game Engine)</h3>\n<p><em>In Castle Game Engine</em> we encourage to use <code>TFreeNotificationObserver</code> from <code>CastleClassUtils</code> unit instead of directly calling <code>FreeNotification</code>, <code>RemoveFreeNotification</code> and overriding <code>Notification</code>.</p>\n<p>In general using <code>TFreeNotificationObserver</code> looks a bit simpler than using <code>FreeNotification</code> mechanism directly (though I admit it is a matter of taste). But in particular when <em>the same class instance must be observed because of multiple reasons</em> then <code>TFreeNotificationObserver</code> is much simpler to use (directly using <code>FreeNotification</code> in this case can get complicated, as you have to watch to not unregister the notification too soon).</p>\n<p>This is the example code using <code>TFreeNotificationObserver</code>, to achieve the same effect as example in the previous section:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>type\n  TControl = class(TComponent)\n  end;</p>\n<p>  TContainer = class(TComponent)\n  private\n    FSomeSpecialControlObserver: TFreeNotificationObserver;\n    FSomeSpecialControl: TControl;\n    procedure SetSomeSpecialControl(const Value: TControl);\n    procedure SomeSpecialControlFreeNotification(const Sender: TFreeNotificationObserver);\n  public\n    constructor Create(AOwner: TComponent); override;\n    property SomeSpecialControl: TControl\n      read FSomeSpecialControl write SetSomeSpecialControl;\n  end;</p>\n<p>implementation</p>\n<p>uses CastleComponentSerialize;</p>\n<p>constructor TContainer.Create(AOwner: TComponent);\nbegin\n  inherited;\n  FSomeSpecialControlObserver := TFreeNotificationObserver.Create(Self);\n  FSomeSpecialControlObserver.OnFreeNotification := {$ifdef FPC}@{$endif} SomeSpecialControlFreeNotification;\nend;</p>\n<p>procedure TContainer.SetSomeSpecialControl(const Value: TControl);\nbegin\n  if FSomeSpecialControl &lt;&gt; Value then\n  begin\n    FSomeSpecialControl := Value;\n    FSomeSpecialControlObserver.Observed := Value;\n  end;\nend;</p>\n<p>procedure TContainer.SomeSpecialControlFreeNotification(const Sender: TFreeNotificationObserver);\nbegin\n  // set property to nil when the referenced component is freed\n  SomeSpecialControl := nil;\nend;</p>\n<hr />\n<p>See <a href=\"https://castle-engine.io/custom_components\" rel=\"nofollow ugc noopener\">https://castle-engine.io/custom_components</a> .</p>\n<h2 id=\"exceptions\">Exceptions</h2>\n<h3 id=\"overview-2\">Overview</h3>\n<p>Exceptions allow to <em>interrupt the normal execution of the code</em>.</p>\n<ul><li>At any point within the program, you can <em>raise</em> an exception using the <code>raise</code> keyword. In effect the lines of code following the <code>raise ...</code>  call will not execute.</li><li><p>An exception may be <em>caught</em> using a <code>try ... except ... end</code> construction. Catching an exception means that you somehow &quot;deal&quot; with exception, and the following code should execute as usual, the exception is no longer propagated upward.</p><p>+\nNote: If an exception is raised but never caught, it will cause the entire application to stop with an error.\n+\n** But in LCL applications, the exceptions are always caught around events (and cause LCL dialog box) if you don&#39;t catch them earlier.\n** In <em>Castle Game Engine</em> applications using <code>CastleWindow</code>, we similarly always catch exceptions around your events (and display proper dialog box).\n** So it is not so easy to make an exception that is <em>not caught anywhere</em> (not caught in your code, LCL code, CGE code...).</p></li><li><p>Although an exception breaks the execution, you can use the <code>try ... finally ... end</code> construction to execute some code <em>always</em>, even if the code was interrupted by an exception.</p><p>+\nThe <code>try ... finally ... end</code> construction also works when code is interrupted by <code>Break</code> or <code>Continue</code> or <code>Exit</code> keywords. The point is to always execute code in the <code>finally</code> section.</p></li></ul>\n<p>An &quot;exception&quot; is, in general, any class instance.</p>\n<ul><li>The compiler does not enforce any particular class. You just must call <code>raise XXX</code> where <code>XXX</code> is an instance of any class. Any class (so, anything descending from <code>TObject</code>) is fine.</li><li>It is a standard convention for exception classes to descend from a special <code>Exception</code> class. The <code>Exception</code> class extends <code>TObject</code>, adding a string <code>Message</code> property and a constructor to easily set this property. All exceptions raised by the standard library descend from <code>Exception</code>. We advise to follow this convention.</li><li>Exception classes (by convention) have names that start with <code>E</code>, not <code>T</code>. Like <code>ESomethingBadHappened</code>.</li><li><p>The compiler will automatically free exception object when it is handled. Don&#39;t free it yourself.</p><p>+\nIn most cases, you just construct the object at the same time when you call <code>raise</code>, like <code>raise ESomethingBadHappened.Create(&#39;Description of what bad thing happened.&#39;)</code>.</p></li></ul>\n<h3 id=\"raising\">Raising</h3>\n<p>If you want to raise your own exception, declare it and call <code>raise ...</code> when appropriate:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>type\n  EInvalidParameter = class(Exception);</p>\n<p>function ReadParameter: String;\nbegin\n  Result := Readln;\n  if Pos(&#39; &#39;, Result) &lt;&gt; 0 then\n    raise EInvalidParameter.Create(&#39;Invalid parameter, space is not allowed&#39;);\nend;</p>\n<hr />\n<p>Note that the expression following the <code>raise</code> should be a valid class instance to raise. You will almost always create the exception instance here.</p>\n<p>You can also use the <code>CreateFmt</code> constructor, which is a comfortable shortcut to <code>Create(Format(MessageFormat, MessageArguments))</code>. This is a common way to provide more information to the exception message. We can improve the previous example like this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>type\n  EInvalidParameter = class(Exception);</p>\n<p>function ReadParameter: String;\nbegin\n  Result := Readln;\n  if Pos(&#39; &#39;, Result) &lt;&gt; 0 then\n    raise EInvalidParameter.CreateFmt(&#39;Invalid parameter %s, space is not allowed&#39;, [Result]);\nend;</p>\n<hr />\n<h3 id=\"catching\">Catching</h3>\n<p>You can catch an exception like this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>var\n  Parameter1, Parameter2, Parameter3: String;\nbegin\n  try\n    WriteLn(&#39;Input 1st parameter:&#39;);\n    Parameter1 := ReadParameter;\n    WriteLn(&#39;Input 2nd parameter:&#39;);\n    Parameter2 := ReadParameter;\n    WriteLn(&#39;Input 3rd parameter:&#39;);\n    Parameter3 := ReadParameter;\n  except\n    // capture EInvalidParameter raised by one of the above ReadParameter calls\n    on EInvalidParameter do\n      WriteLn(&#39;EInvalidParameter exception occurred&#39;);\n  end;\nend;</p>\n<hr />\n<p>To improve the above example, we can declare the name for the exception instance (we will use <code>E</code> in the example). This way we can print the exception message:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>try\n...\nexcept\n  on E: EInvalidParameter do\n    WriteLn(&#39;EInvalidParameter exception occurred with message: &#39; + E.Message);\nend;</p>\n<hr />\n<p>One could also test for multiple exception classes:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>try\n...\nexcept\n  on E: EInvalidParameter do\n    WriteLn(&#39;EInvalidParameter exception occurred with message: &#39; + E.Message);\n  on E: ESomeOtherException do\n    WriteLn(&#39;ESomeOtherException exception occurred with message: &#39; + E.Message);\nend;</p>\n<hr />\n<p>You can also react to any exception raised, if you don&#39;t use any <code>on</code> expression:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>try\n...\nexcept\n  WriteLn(&#39;Warning: Some exception occurred&#39;);\nend;\n// WARNING: DO NOT FOLLOW THIS EXAMPLE WITHOUT READING A WARNING BELOW\n// ABOUT &quot;CAPTURING ALL EXCEPTIONS&quot;</p>\n<hr />\n<p>In general <em>you should only catch exceptions of a specific class, that signal a particular problem that you know what to do with</em>. Be careful with catching exceptions of a general type (like catching any <code>Exception</code> or any <code>TObject</code>), as you may easily catch too much, and later cause troubles when debugging other problems. As in all programming languages with exceptions, the good rule to follow is to <em>never capture an exception that you do not know how to handle</em>. In particular, do not capture an exception just as a simple workaround of the problem, without investigating first <em>why</em> the exception occurs.</p>\n<ul><li>Does the exception indicate a problem in user input? Then you should report it to user.</li><li>Does the exception indicate a bug in your code? Then you should fix the code, to avoid the exception from happening at all.</li></ul>\n<p>Another way to capture all exceptions is to use:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>try\n...\nexcept\n  on E: TObject do\n    WriteLn(&#39;Warning: Some exception occurred&#39;);\nend;\n// WARNING: DO NOT FOLLOW THIS EXAMPLE WITHOUT READING A WARNING ABOVE\n// ABOUT &quot;CAPTURING ALL EXCEPTIONS&quot;</p>\n<hr />\n<p>Although usually it is enough to capture <code>Exception</code>:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>try\n...\nexcept\n  on E: Exception do\n    WriteLn(&#39;Warning: Some exception occurred: &#39; + E.ClassName + &#39;, message: &#39; + E.Message);\nend;\n// WARNING: DO NOT FOLLOW THIS EXAMPLE WITHOUT READING A WARNING ABOVE\n// ABOUT &quot;CAPTURING ALL EXCEPTIONS&quot;</p>\n<hr />\n<p>You can &quot;re-raise&quot; the exception in the <code>except ... end</code> block, if you decide so. You can just do <code>raise E</code> if the exception instance is <code>E</code>, you can also just use parameter-less <code>raise</code>. For example:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>try\n...\nexcept\n  on E: EInvalidSoundFile do\n  begin\n    if E.InvalidUrl = &#39;<a href=\"http://example.com/blablah.wav\" rel=\"nofollow ugc noopener\">http://example.com/blablah.wav</a>&#39; then\n      WriteLn(&#39;Warning: loading <a href=\"http://example.com/blablah.wav\" rel=\"nofollow ugc noopener\">http://example.com/blablah.wav</a> failed, ignore it&#39;)\n    else\n      raise;\n  end;\nend;</p>\n<hr />\n<p>Note that, although the exception is an instance of an object, you should never manually free it after raising. The compiler will generate proper code that makes sure to free the exception object once it&#39;s handled.</p>\n<h3 id=\"finally-doing-things-regardless-of-whether-an-exception-occurred\">Finally (doing things regardless of whether an exception occurred)</h3>\n<p>Often you use <code>try .. finally .. end</code> construction to free an instance of some object, regardless of whether an exception occurred when using this object. The way to write it looks like this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>procedure MyProcedure;\nvar\n  MyInstance: TMyClass;\nbegin\n  MyInstance := TMyClass.Create;\n  try\n    MyInstance.DoSomething;\n    MyInstance.DoSomethingElse;\n  finally\n    FreeAndNil(MyInstance);\n  end;\nend;</p>\n<hr />\n<p>This always works, and does not cause memory leaks, even if <code>MyInstance.DoSomething</code> or <code>MyInstance.DoSomethingElse</code> raise an exception.</p>\n<p>Note that this takes into account that local variables, like <code>MyInstance</code> above, have undefined values (may contain random &quot;memory garbage&quot;) before the first assignment. That is, writing something like this would <em>not</em> be valid:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>// INCORRECT EXAMPLE:\nprocedure MyProcedure;\nvar\n  MyInstance: TMyClass;\nbegin\n  try\n    CallSomeOtherProcedure;\n    MyInstance := TMyClass.Create;\n    MyInstance.DoSomething;\n    MyInstance.DoSomethingElse;\n  finally\n    FreeAndNil(MyInstance);\n  end;\nend;</p>\n<hr />\n<p>The above example is not valid: if an exception occurs within <code>TMyClass.Create</code> (a constructor may also raise an exception), or within the <code>CallSomeOtherProcedure</code>, then the <code>MyInstance</code> variable is not initialized. Calling <code>FreeAndNil(MyInstance)</code> will try to call destructor of <code>MyInstance</code>, which will most likely crash with <em>Access Violation (Segmentation Fault)</em> error. In effect, one exception causes another exception, which will make the error report not very useful: you will not see the message of the original exception.</p>\n<p>Sometimes it is justified to fix the above code by first initializing all local variables to <code>nil</code> (on which calling <code>FreeAndNil</code> is safe, and will not do anything). This makes sense if you free a <em>lot</em> of class instances. So the two code examples below work equally well:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>procedure MyProcedure;\nvar\n  MyInstance1: TMyClass1;\n  MyInstance2: TMyClass2;\n  MyInstance3: TMyClass3;\nbegin\n  MyInstance1 := TMyClass1.Create;\n  try\n    MyInstance1.DoSomething;</p>\n<pre><code>MyInstance2 := TMyClass2.Create;\ntry\n  MyInstance2.DoSomethingElse;\n\n  MyInstance3 := TMyClass3.Create;\n  try\n    MyInstance3.DoYetAnotherThing;\n  finally\n    FreeAndNil(MyInstance3);\n  end;\nfinally\n  FreeAndNil(MyInstance2);\nend;</code></pre>\n<p>  finally\n    FreeAndNil(MyInstance1);\n  end;\nend;</p>\n<hr />\n<p>It is probably more readable in the form below:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>procedure MyProcedure;\nvar\n  MyInstance1: TMyClass1;\n  MyInstance2: TMyClass2;\n  MyInstance3: TMyClass3;\nbegin\n  MyInstance1 := nil;\n  MyInstance2 := nil;\n  MyInstance3 := nil;\n  try\n    MyInstance1 := TMyClass1.Create;\n    MyInstance1.DoSomething;</p>\n<pre><code>MyInstance2 := TMyClass2.Create;\nMyInstance2.DoSomethingElse;\n\nMyInstance3 := TMyClass3.Create;\nMyInstance3.DoYetAnotherThing;</code></pre>\n<p>  finally\n    FreeAndNil(MyInstance3);\n    FreeAndNil(MyInstance2);\n    FreeAndNil(MyInstance1);\n  end;\nend;</p>\n<hr />\n<p>NOTE: In this simple example, you could also make a valid argument that the code should be split into 3 separate procedures, one calling each other.</p>\n<p>The final section in the <code>try .. finally .. end</code> block executes in most possible scenarios when you leave the main code. Consider this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>try\n  A;\nfinally\n  B;\nend;</p>\n<hr />\n<p>So <code>B</code> will execute if</p>\n<ul><li>The <code>A</code> raised (and didn&#39;t catch) an exception.</li><li>Or you will call <code>Exit</code> or (if you&#39;re in the loop) <code>Break</code> or <code>Continue</code> right after calling <code>A</code>.</li><li>Or none of the above happened, and the code in <code>A</code> just executed without any exception, and you didn&#39;t call <code>Exit</code>, <code>Break</code> or <code>Continue</code> either.</li></ul>\n<p>The only way to really avoid the <code>B</code> being executed is to unconditionally interrupt the application process using <code>Halt</code> or some platform-specific APIs (like <a href=\"https://www.man7.org/linux/man-pages/man3/exit.3.html[libc\" rel=\"nofollow ugc noopener\">https://www.man7.org/linux/man-pages/man3/exit.3.html[libc</a> exit on Unix]) inside <code>A</code>. Which generally should not be done -- it&#39;s more flexible to use exceptions to interrupt the application, because it allows some other code to have a chance to clean up.</p>\n<p>NOTE: The <code>try .. finally .. end</code> doesn&#39;t catch the exception. The exception will still propagate upward, and can be caught by the <code>try .. except .. end</code> block outside of this one.</p>\n<p>An example of <code>try .. finally .. end</code> together with <code>Exit</code> calls:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>procedure MyProcedure;\nbegin\n  try\n    WriteLn(&#39;Do something&#39;);\n    Exit;\n    WriteLn(&#39;This will not happen&#39;);\n  finally\n    WriteLn(&#39;This will happen regardless of whether we have left the block through Exception, Exit, Continue, Break, etc.&#39;);\n  end;\n  WriteLn(&#39;This will not happen&#39;);\nend;</p>\n<hr />\n<p>See the &lt;&lt;Exceptions&gt;&gt; chapter for more in-depth description of <em>exceptions</em> including how to <code>raise</code> them and use <code>try ... except ... end</code> to catch them.</p>\n<h3 id=\"how-the-exceptions-are-displayed-by-various-libraries\">How the exceptions are displayed by various libraries</h3>\n<ul><li>In case of Lazarus LCL, the exceptions raised during events (various callbacks assigned to <code>OnXxx</code> properties of LCL components) will be captured and will result in a nice dialog message, that allows the user to continue and stop the application. This means that your own exceptions do not &quot;get out&quot; from <code>Application.ProcessMessages</code>, so they do not automatically break the application. You can configure what happens using <code>TApplicationProperties.OnException</code>.</li><li>Similarly in case of <em>Castle Game Engine</em> with <code>CastleWindow</code>: the exception is internally captured and results in nice error message. So exceptions do not &quot;get out&quot; from <code>Application.ProcessMessages</code>. Again, you can configure what happens using <code>Application.OnException</code>.</li><li>Some other GUI libraries may do a similar thing to above.</li><li>In case of other applications, you can configure how the exception is displayed by assigning a global callback to <code>OnHaltProgram</code>.</li></ul>\n<h2 id=\"run-time-library\">Run-time library</h2>\n<h3 id=\"input-output-using-streams\">Input/output using streams</h3>\n<p>Modern programs should use <code>TStream</code> class and its many descendants to do input / output. It has many useful descendants, like <code>TFileStream</code>, <code>TMemoryStream</code>, <code>TStringStream</code>.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/file_stream.dpr[]</p>\n<hr />\n<p><em>In the Castle Game Engine</em>: You should use the <code>Download</code> function to create a stream that obtains data from any URL. Regular files, HTTP and HTTPS resources, Android assets and more are supported this way. Moreover, to open the resource inside your game data (in the <code>data</code> subdirectory) use the special <code>castle-data:/xxx</code> URL. Examples:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>EnableNetwork := true;\nS := Download(&#39;<a href=\"https://castle-engine.io/latest.zip\" rel=\"nofollow ugc noopener\">https://castle-engine.io/latest.zip</a>&#39;);</p>\n<hr />\n<p>[source,pascal]</p>\n<hr />\n<p>S := Download(&#39;file:///home/michalis/my_binary_file.data&#39;);</p>\n<hr />\n<p>[source,pascal]</p>\n<hr />\n<p>S := Download(&#39;castle-data:/gui/my_image.png&#39;);</p>\n<hr />\n<p>To read text files, we advise using the <code>TCastleTextReader</code> class. It provides a line-oriented API, and wraps a <code>TStream</code> inside. The <code>TCastleTextReader</code> constructor can take a ready URL, or you can pass there your custom <code>TStream</code> source.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>Text := TCastleTextReader.Create(&#39;castle-data:/my_data.txt&#39;);\ntry\n  while not Text.Eof do\n    WriteLnLog(&#39;NextLine&#39;, Text.ReadLn);\nfinally\n  FreeAndNil(Text);\nend;</p>\n<hr />\n<p>Documentation of all the <em>Castle Game Engine</em> features to load and save streams, including the <code>Download</code> function and the <code>TCastleTextReader</code> class, is on <a href=\"https://castle-engine.io/url\" rel=\"nofollow ugc noopener\">https://castle-engine.io/url</a> .</p>\n<h3 id=\"containers-lists-dictionaries-using-generics\">Containers (lists, dictionaries) using generics</h3>\n<p>The language and run-time library offer various flexible containers. There are a number of non-generic classes (like <code>TList</code> and <code>TObjectList</code> from the <code>Contnrs</code> unit), there are also dynamic arrays (<code>array of TMyType</code>). But to get the most flexibility <em>and</em> type-safety, I advise using <em>generic containers</em> for most of your needs.</p>\n<p>The <em>generic containers</em> give you a lot of helpful methods to add, remove, iterate, search, sort... The compiler also knows (and checks) that the container holds only items of the appropriate type.</p>\n<p>// Using these lists is a good idea, as you get type-safety, and their API is rich (there are methods to find, sort, iterate and so on). We discourage using <em>dynamic arrays</em> (<code>array of X</code>, <code>SetLength(X, ...)</code>) as their API is poor (you can only use <code>SetLength</code> and your own type helpers). We discourage using <code>TList</code> or <code>TObjectList</code> as it will require casting your references from <code>TObject</code> to your type.</p>\n<p>There are three libraries providing generics containers in FPC now:</p>\n<ul><li><code>Generics.Collections</code> unit and friends (since FPC &gt;= 3.2.0)</li><li><code>FGL</code> unit</li><li><code>GVector</code> unit and friends (together in <code>fcl-stl</code>)</li></ul>\n<p>We advise using the <code>Generics.Collections</code> unit. The generic containers it implements are</p>\n<ul><li>packed with useful features,</li><li>very efficient (in particular important for accessing dictionaries by keys),</li><li>compatible between FPC and Delphi,</li><li>the naming is consistent with other parts of the standard library (like the non-generic containers from the <code>Contnrs</code> unit).</li></ul>\n<p><em>In the Castle Game Engine</em>: We use the <code>Generics.Collections</code> intensively throughout the engine, and advise you to use <code>Generics.Collections</code> in your applications too!</p>\n<p>Most important classes from the <code>Generics.Collections</code> unit are:</p>\n<p>TList:: A generic list of types.\nTObjectList:: A generic list of object instances. It can &quot;own&quot; children, which means that it will free them automatically.\nTDictionary:: A generic dictionary.\nTObjectDictionary:: A generic dictionary, that can &quot;own&quot; the keys and/or values.\n// So (which means that they should be object instances, and will be automatically freed).</p>\n<p>Here&#39;s how to use a simple generic <code>TObjectList</code>:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/generics_lists.dpr[]</p>\n<hr />\n<p>Note that some operations require comparing two items, like sorting and searching (e.g. by <code>Sort</code> and <code>IndexOf</code> methods). The <code>Generics.Collections</code> containers use a <em>comparer</em> for this. The <em>default comparer</em> is reasonable for all types, even for records (in which case it compares memory contents, which is a reasonable default at least for searching using <code>IndexOf</code>).\n// It can be customized if needed.</p>\n<p>When sorting the list you can provide a <em>custom comparer</em> as a parameter. The <em>comparer</em> is a class implementing the <code>IComparer</code> interface. In practice, you usually define the appropriate callback, and use <code>TComparer&lt;T&gt;.Construct</code> method to wrap this callback into an <code>IComparer</code> instance. An example of doing this is below:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/generics_sorting.dpr[]</p>\n<hr />\n<p>The <code>TDictionary</code> class implements a <em>dictionary</em>, also known as a <em>map (key -&gt; value)</em>, also known as an <em>associative array</em>. Its API is a bit similar to the C# <code>TDictionary</code> class. It has useful iterators for keys, values, and pairs of key-&gt;value.</p>\n<p>An example using a dictionary:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/generics_dictionary.dpr[]</p>\n<hr />\n<p>The <code>TObjectDictionary</code> can additionally <em>own</em> the dictionary keys and/or values, which means that they will be automatically freed. Be careful to <em>only own keys and/or values if they are object instances</em>. If you set to <em>&quot;owned&quot;</em> some other type, like an <code>Integer</code> (for example, if your keys are <code>Integer</code>, and you include <code>doOwnsKeys</code>), you will get a nasty crash when the code executes.</p>\n<p>An example code using the <code>TObjectDictionary</code> is below. Compile this example with <em>memory leak detection</em>, like <code>fpc -gl -gh generics_object_dictionary.dpr</code>, to see that everything is freed when program exits.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/generics_object_dictionary.dpr[]</p>\n<hr />\n<p>If you prefer using the <code>FGL</code> unit instead of <code>Generics.Collections</code>, the most important classes from the <code>FGL</code> unit are:</p>\n<p>TFPGList:: A generic list of types.\nTFPGObjectList:: A generic list of object instances. It can &quot;own&quot; children.\nTFPGMap:: A generic dictionary.</p>\n<p>//Use <code>TFPGList</code> for lists of primitives (or records or old-style objects), <code>TFPGObjectList</code> for a list of class instances. <em>In the Castle Game Engine:</em> You can also use <code>CastleGenericLists</code> with <code>TGenericStructList</code> for a list of records or old-style objects, this workarounds the problem of impossibility to override their operators in older FPC versions.</p>\n<p>In <code>FGL</code> unit, the <code>TFPGList</code> can be only used for types for which the equality operator (=) is defined. For <code>TFPGMap</code> the <em>&quot;greater than&quot;</em> (&gt;) and <em>&quot;less than&quot;</em> (&lt;) operators must be defined for the key type. If you want to use these lists with types that don&#39;t have built-in comparison operators (e.g. with records), you have to overload their operators as shown in the &lt;&lt;Operator overloading&gt;&gt;.</p>\n<p><em>In the Castle Game Engine</em> we include a unit <code>CastleGenericLists</code> that adds <code>TGenericStructList</code> and <code>TGenericStructMap</code> classes. They are similar to <code>TFPGList</code> and <code>TFPGMap</code>, but they do not require a definition of the comparison operators for the appropriate type (instead, they compare memory contents, which is often appropriate for records or method pointers). But the <code>CastleGenericLists</code> unit is deprecated since the engine version 6.3, as we advise using <code>Generics.Collections</code> instead.</p>\n<p>If you want to know more about the generics, see &lt;&lt;Generics&gt;&gt;.</p>\n<h3 id=\"cloning-tpersistent-assign\">Cloning: TPersistent.Assign</h3>\n<p>Copying the class instances by a simple assignment operator copies the <em>reference</em>.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>var\n  X, Y: TMyObject;\nbegin\n  X := TMyObject.Create;\n  Y := X;\n  // X and Y are now two pointers to the same data\n  Y.MyField := 123; // this also changes X.MyField\n  FreeAndNil(X);\nend;</p>\n<hr />\n<p>To copy the <em>class instance contents</em>, the standard approach is to derive your class from <code>TPersistent</code>, and override its <code>Assign</code> method. Once it&#39;s implemented properly in <code>TMyObject</code>, you use it like this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>var\n  X, Y: TMyObject;\nbegin\n  X := TMyObject.Create;\n  Y := TMyObject.Create;\n  Y.Assign(X);\n  Y.MyField := 123; // this does not change X.MyField\n  FreeAndNil(X);\n  FreeAndNil(Y);\nend;</p>\n<hr />\n<p>To make it work, you need to implement the <code>Assign</code> method to actually copy the fields you want. You should carefully implement the <code>Assign</code> method, to copy from a class that may be a descendant of the current class.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/persistent.dpr[]</p>\n<hr />\n<p>Sometimes it&#39;s more comfortable to alternatively override the <code>AssignTo</code> method in the source class, instead of overriding the <code>Assign</code> method in the destination class.</p>\n<p>Be careful when you call <code>inherited</code> in the overridden <code>Assign</code> implementation. There are two situations:</p>\n<p>Your class is a direct descendant of the <code>TPersistent</code> class. (Or, it&#39;s not a direct descendant of <code>TPersistent</code>, but no ancestor has overridden the <code>Assign</code> method.)::</p>\n<p>  In this case, your class should use the <code>inherited</code> keyword (to call the <code>TPersistent.Assign</code>) <em>only if you cannot handle the assignment in your code</em>.</p>\n<p>Your class descends from some class that has already overridden the <code>Assign</code> method.::</p>\n<p>  In this case, your class should <em>always</em> use the <code>inherited</code> keyword (to call the ancestor <code>Assign</code>). In general, calling <code>inherited</code> in overridden methods is <em>usually</em> a good idea.</p>\n<p>To understand the reason behind the above rule (when you should call, and when you should <em>not</em> call <code>inherited</code> from the <code>Assign</code> implementation), and how it relates to the <code>AssignTo</code> method, let&#39;s look at the <code>TPersistent.Assign</code> and <code>TPersistent.AssignTo</code> implementations:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>procedure TPersistent.Assign(Source: TPersistent);\nbegin\n  if Source &lt;&gt; nil then\n    Source.AssignTo(Self)\n  else\n    raise EConvertError...\nend;</p>\n<p>procedure TPersistent.AssignTo(Destination: TPersistent);\nbegin\n  raise EConvertError...\nend;</p>\n<hr />\n<p>NOTE: This is not the <em>exact</em> implementation of <code>TPersistent</code>. I copied the FPC standard library code, but then I simplified it to hide unimportant details about the exception message.\n//The exact source code, in the FPC standard library, can be found in the <code>rtl/objpas/classes/persist.inc</code> source file. Its behavior is 100% compatible with the Delphi standard library, as far as I know.</p>\n<p>The conclusions you can get from the above are:</p>\n<ul><li><em>If neither <code>Assign</code> nor <code>AssignTo</code> are overridden</em>, then calling them will result in an exception.</li><li>Also, note that there is <em>no</em> code in <code>TPersistent</code> implementation that automatically copies all the fields (or all the published fields) of the classes. That&#39;s why you need to do that yourself, by overriding <code>Assign</code> in all the classes. You can use RTTI (runtime type information) for that, but for simple cases you will probably just list the fields to be copied manually.</li></ul>\n<p>When you have a class like <code>TApple</code>, your <code>TApple.Assign</code> implementation usually deals with copying fields that are specific to the <code>TApple</code> class (not to the <code>TApple</code> ancestor, like <code>TFruit</code>). So, the <code>TApple.Assign</code> implementation usually checks whether <code>Source is TApple</code> at the beginning, before copying apple-related fields. Then, it calls <code>inherited</code> to allow <code>TFruit</code> to handle the rest of the fields.</p>\n<p>Assuming that you implemented <code>TFruit.Assign</code> and <code>TApple.Assign</code> following the standard pattern (as shown in the example above), the effect is like this:</p>\n<ul><li>If you pass <code>TApple</code> instance to <code>TApple.Assign</code>, it will work and copy all the fields.</li><li>If you pass <code>TOrange</code> instance to <code>TApple.Assign</code>, it will work and only copy the common fields shared by both <code>TOrange</code> and <code>TApple</code>. In other words, the fields defined at <code>TFruit</code>.</li><li>If you pass <code>TWerewolf</code> instance to <code>TApple.Assign</code>, it will raise an exception (because <code>TApple.Assign</code> will call <code>TFruit.Assign</code> which will call <code>TPersistent.Assign</code> which raises an exception).</li></ul>\n<p>NOTE: Remember that when descending from <code>TPersistent</code>, the default <em>visibility specifier</em> is <code>published</code>, to allow streaming of <code>TPersistent</code> descendants. Not all field and property types are allowed in the <code>published</code> section. If you get errors related to it, and you don&#39;t care about streaming, just change the visibility to <code>public</code>. See the &lt;&lt;Visibility specifiers&gt;&gt;.</p>\n<h2 id=\"various-language-features\">Various language features</h2>\n<h3 id=\"local-nested-routines\">Local (nested) routines</h3>\n<p>Inside a larger <em>routine</em> (function, procedure, method) you can define a helper routine.</p>\n<p>//It has all the flexibility of a normal routine, it&#39;s just not\n//This is quite powerful feature that allows you to <em>easily</em> split a long routine into many smaller ones.</p>\n<p>The local routine can freely access (read and write) all the parameters of a parent, <em>and all the local variables of the parent that were declared above it</em>. This is very powerful. It often allows to split long routines into a couple of small ones without much effort (as you don&#39;t have to pass around all the necessary information in the parameters). Be careful to not overuse this feature -- if many nested functions use (and even change) the same variable of the parent, the code may get hard to follow.</p>\n<p>These two examples are equivalent:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>function SumOfSquares(const N: Integer): Integer;</p>\n<p>  function Square(const Value: Integer): Integer;\n  begin\n    Result := Value * Value;\n  end;</p>\n<p>var\n  I: Integer;\nbegin\n  Result := 0;\n  for I := 0 to N do\n    Result := Result + Square(I);\nend;</p>\n<hr />\n<p>Another version, where we let the local routine <code>Square</code> to access <code>I</code> directly:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>function SumOfSquares(const N: Integer): Integer;\nvar\n  I: Integer;</p>\n<p>  function Square: Integer;\n  begin\n    Result := I * I;\n  end;</p>\n<p>begin\n  Result := 0;\n  for I := 0 to N do\n    Result := Result + Square;\nend;</p>\n<hr />\n<p>Local routines can go to any depth -- which means that you can define a local routine within another local routine. So you can go wild (but please don&#39;t go <em>too wild</em>, or the code will get unreadable:).</p>\n<h3 id=\"callbacks-aka-events-aka-pointers-to-functions-aka-procedural-va\">Callbacks (aka events, aka pointers to functions, aka procedural variables)</h3>\n<p>They allow to call a function indirectly, through to a variable. The variable can be assigned at runtime to point to any function <em>with matching parameter types and return types</em>.</p>\n<p>The callback can be:</p>\n<ul><li><p>Normal, which means it can point to any normal routine (not a method, not local).</p><p>+\n[source,pascal]</p></li></ul>\n<hr />\n<p>include::modern_pascal_code_samples/callbacks.dpr[]</p>\n<hr />\n<ul><li><p>A method: declare with <code>of object</code> at the end.</p><p>+\n[source,pascal]</p></li></ul>\n<hr />\n<p>include::modern_pascal_code_samples/callbacks_of_object.dpr[]</p>\n<hr />\n<p>+\nNote that you <em>cannot</em> pass global procedures / functions as methods. They are incompatible. If you have to provide an <code>of object</code> callback, but don&#39;t want to create a dummy class instance, you can pass &lt;&lt;Class methods&gt;&gt; as methods.\n+\n[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/callbacks_of_object_class_methods.dpr[]</p>\n<hr />\n<ul><li>A (possibly) local routine: declare with <code>is nested</code> at the end, and make sure to use <code>{$modeswitch nestedprocvars}</code> directive for the code. These go hand-in-hand with &lt;&lt;Local (nested) routines&gt;&gt;.</li></ul>\n<h3 id=\"anonymous-functions\">Anonymous functions</h3>\n<p>Delphi and new FPC versions (&gt;= 3.3.1) support:</p>\n<ul><li>anonymous functions (define function implementation right when you assign it to a variable or pass as an argument),</li><li>and function references (a new type of &quot;function callback&quot; that can accept a wide range of function types, including global functions, methods and anonymous functions).</li></ul>\n<p>Example:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/anon_functions_list_map_foreach.dpr[]</p>\n<hr />\n<p>More information:</p>\n<ul><li>Delphi documentation: <a href=\"https://docwiki.embarcadero.com/RADStudio/Sydney/en/Anonymous_Methods_in_Delphi\" rel=\"nofollow ugc noopener\">https://docwiki.embarcadero.com/RADStudio/Sydney/en/Anonymous_Methods_in_Delphi</a></li><li>FPC forum post: <a href=\"https://forum.lazarus.freepascal.org/index.php/topic,59468.0.html\" rel=\"nofollow ugc noopener\">https://forum.lazarus.freepascal.org/index.php/topic,59468.0.html</a></li><li>FPC feature changelog: <a href=\"https://wiki.freepascal.org/FPC_New_Features_Trunk#Support_for_Function_References_and_Anonymous_Functions\" rel=\"nofollow ugc noopener\">https://wiki.freepascal.org/FPC_New_Features_Trunk#Support_for_Function_References_and_Anonymous_Functions</a></li></ul>\n<p>To get FPC 3.3.1, we recommend to use FpcUpDeluxe: <a href=\"https://castle-engine.io/fpcupdeluxe\" rel=\"nofollow ugc noopener\">https://castle-engine.io/fpcupdeluxe</a> .</p>\n<h3 id=\"generics\">Generics</h3>\n<p>A powerful feature of any modern language. The definition of something (typically, of a class) can be parameterized with another type. The most typical example is when you need to create a container (a list, dictionary, tree, graph...): you can define <em>a list of type T</em>, and then <em>specialize</em> it to instantly get <em>a list of integers</em>, <em>a list of strings</em>, <em>a list of TMyRecord</em>, and so on.</p>\n<p>The generics in Pascal work much like generics in C++. Which means that they are <em>&quot;expanded&quot;</em> at specialization time, a <em>little</em> like macros (but much safer than macros; for example, the identifiers are resolved at the time of generic definition, not at specialization, so you cannot &quot;inject&quot; any unexpected behavior when specializing the generic). In effect this means that they are very fast (can be optimized for each particular type) and work with types of any size. You can use a primitive type (integer, float) as well as a record, as well as a class when specializing a generic.</p>\n<p>// Unlike in Java, you are <em>not</em> limited to only generics of things that are a reference.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/generics.dpr[]</p>\n<hr />\n<p>Generics are not limited to classes, you can have generic functions and procedures as well:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/generic_functions.dpr[]</p>\n<hr />\n<p>See also the &lt;&lt;generic-containers-section&gt;&gt; about important standard classes using generics.</p>\n<h3 id=\"overloading\">Overloading</h3>\n<p>Methods (and global functions and procedures) with the same name are allowed, as long as they have different parameters. At compile time, the compiler detects which one you want to use, knowing the parameters you pass.</p>\n<p>By default, the overloading uses the FPC approach, which means that all the methods in given namespace (a class or a unit) are equal, and hide the other methods in namespaces with less priority. For example, if you define a class with methods <code>Foo(Integer)</code> and <code>Foo(string)</code>, and it descends from a class with method <code>Foo(Float)</code>, then the users of your new class will not be able to access the method <code>Foo(Float)</code> easily (they still can --- if they typecast the class to its ancestor type). To overcome this, use the <code>overload</code> keyword.</p>\n<h3 id=\"preprocessor\">Preprocessor</h3>\n<p>You can use simple preprocessor directives for</p>\n<ul><li>conditional compilation (code depending on platform, or some custom switches),</li><li>to include one file in another,</li><li>you can also use parameter-less macros.</li></ul>\n<p>Note that macros with parameters are not allowed. In general, you should avoid using the preprocessor stuff... unless it&#39;s really justified. The preprocessing happens before parsing, which means that you can &quot;break&quot; the normal syntax of the Pascal language. This is a powerful, but also somewhat dirty, feature.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>unit PreprocessorStuff;</p>\n<p>{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}</p>\n<p>interface</p>\n<p>{$ifdef FPC}\n{ This is only defined when compiled by FPC, not other compilers (like Delphi). }\nprocedure Foo;\n{$endif}</p>\n<p>{ Define a NewLine constant. Here you can see how the normal syntax of Pascal\n  is &quot;broken&quot; by preprocessor directives. When you compile on Unix\n  (includes Linux, Android, macOS), the compiler sees this:</p>\n<pre><code>const NewLine = #10;</code></pre>\n<p>  When you compile on Windows, the compiler sees this:</p>\n<pre><code>const NewLine = #13#10;</code></pre>\n<p>  On other operating systems, the code will fail to compile,\n  because a compiler sees this:</p>\n<pre><code>const NewLine = ;</code></pre>\n<p>  It&#39;s a <em>good</em> thing that the compilation fails in this case -- if you\n  will have to port the program to an OS that is not Unix, not Windows,\n  you will be reminded by a compiler to choose the newline convention\n  on that system. }</p>\n<p>const\n  NewLine =\n    {$ifdef UNIX} #10 {$endif}\n    {$ifdef MSWINDOWS} #13#10 {$endif} ;</p>\n<p>{$define MY_SYMBOL}</p>\n<p>{$ifdef MY_SYMBOL}\nprocedure Bar;\n{$endif}</p>\n<p>{$define CallingConventionMacro := unknown}\n{$ifdef UNIX}\n  {$define CallingConventionMacro := cdecl}\n{$endif}\n{$ifdef MSWINDOWS}\n  {$define CallingConventionMacro := stdcall}\n{$endif}\nprocedure RealProcedureName; CallingConventionMacro; external &#39;some_external_library&#39;;</p>\n<p>implementation</p>\n<p>{$include some_file.inc}\n// $I is just a shortcut for $include\n{$I some_other_file.inc}</p>\n<p>end.</p>\n<hr />\n<p>Include files have commonly the <code>.inc</code> extension, and are used for two purposes:</p>\n<ul><li><p>The include file may only contain other compiler directives, that &quot;configure&quot; your source code. For example you could create a file <code>myconfig.inc</code> with these contents:</p><p>+\n[source,pascal]</p></li></ul>\n<hr />\n<p>include::modern_pascal_code_samples/myconfig.inc[]</p>\n<hr />\n<p>+\nNow you can include this file using <code>{$I myconfig.inc}</code> in all your sources.</p>\n<ul><li><p>The other common use is to split a large unit into many files, while still keeping it a single unit as far as the language rules are concerned. Do not overuse this technique -- your first instinct should be to split a single unit into multiple units, not to split a single unit into multiple include files. Nevertheless, this is a useful technique.</p><p>. It allows to avoid &quot;exploding&quot; the number of units, while still keeping your source code files short. For example, it may be better to have a single unit with <em>&quot;commonly used UI controls&quot;</em> than to create <em>one unit for each UI control class</em>, as the latter approach would make the typical &quot;uses&quot; clause long (since a typical UI code will depend on a couple of UI classes). But placing all these UI classes in a single <code>myunit.pas</code> file would make it a long file, unhandy to navigate, so splitting it into multiple include files may make sense.\n//For example, <em>Castle Game Engine</em> has a unit <code>CastleControls</code> with a couple of user-interface controls, like <code>TCastleButton</code>, <code>TCastleLabel</code>, <code>TCastleImageControl</code> and more. We could split it into many units, even to <em>one unit per class</em>, as the classes are not really tightly connected. But that would often force you to have a long <code>uses</code> clause, since a lot of user-interface code will want to use a couple of control classes. So we made a practical decision to just put all <em>often used controls</em> in a single unit.\n. It allows to have a cross-platform unit interface with platform-dependent implementation easily. Basically you can do\n+\n[source,pascal]</p></li></ul>\n<hr />\n<p>{$ifdef UNIX} {$I my_unix_implementation.inc} {$endif}\n{$ifdef MSWINDOWS} {$I my_windows_implementation.inc} {$endif}</p>\n<hr />\n<p>+\nSometimes this is better than writing a long code with many <code>{$ifdef UNIX}</code>, <code>{$ifdef MSWINDOWS}</code> intermixed with normal code (variable declarations, routine implementation). The code is more readable this way. You can even use this technique more aggressively, by using the <code>-Fi</code> command-line option of FPC to include some subdirectories only for specific platforms. Then you can have many version of include file <code>{$I my_platform_specific_implementation.inc}</code> and you simply include them, letting the compiler find the correct version.</p>\n<h3 id=\"records\">Records</h3>\n<p>A <em>record</em> is just a container for other variables. It&#39;s like a much, much simplified <em>class</em>: there is no inheritance or virtual methods. It is like a <em>structure</em> in C-like languages.</p>\n<p>If you use the <code>{$modeswitch advancedrecords}</code> directive, records <em>can</em> have methods and visibility specifiers. In general, language features that are available for classes, and <em>do not break the simple predictable memory layout of a record</em>, are then possible.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/records.dpr[]</p>\n<hr />\n<p>In modern Object Pascal, your first instinct should be to design a <code>class</code>, not a <code>record</code> -- because classes are packed with useful features, like constructors and inheritance.</p>\n<p>But records are still very useful when you need speed or a predictable memory layout:</p>\n<ul><li>Records do not have any constructor or destructor. You just define a variable of a record type. It has undefined contents (memory garbage) at the beginning (except auto-managed types, like strings; they are guaranteed to be initialized to be empty, and finalized to free the reference count). So you have to be more careful when dealing with records, but it gives you some performance gain.</li><li>Arrays of records are nicely linear in memory, so they are cache-friendly.</li><li><p>The memory layout of records (size, padding between fields) is clearly defined in some situations: when you request the <em>C layout</em>, or when you use <code>packed record</code>. This is useful:</p><p>** to communicate with libraries written in other programming languages, when they expose an API based on records,\n** to read and write binary files,\n** to implement dirty low-level tricks (like unsafe typecasting one type to another, being aware of their memory representation).</p></li><li>Records can also have <code>case</code> parts, which work like <em>unions</em> in C-like languages. They allows to treat the same memory piece as a different type, depending on your needs. As such, this allows for greater memory efficiency in some cases. And it allows for more <em>dirty, low-level unsafe tricks</em>:)</li></ul>\n<h3 id=\"variant-records-and-related-concepts\">Variant records and related concepts</h3>\n<p>The concept <em>variant</em> may refer to 3 distinct (though, deep down related) things in Pascal:</p>\n<h4 id=\"variant-records\">Variant records</h4>\n<p><em>Variant records</em> allow to define a section at the end of your record where the same memory can be accessed by a few different names/types.</p>\n<p>This is described on <a href=\"https://en.wikipedia.org/wiki/Tagged_union\" rel=\"nofollow ugc noopener\">https://en.wikipedia.org/wiki/Tagged_union</a> on Wikipedia. <em>&quot;Union&quot;</em> is more common name for this in other languages. See also <a href=\"https://www.freepascal.org/docs-html/ref/refsu15.html\" rel=\"nofollow ugc noopener\">https://www.freepascal.org/docs-html/ref/refsu15.html</a> .</p>\n<p>Example:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/variant_in_record.dpr[]</p>\n<hr />\n<h4 id=\"variant-type\">Variant type</h4>\n<p><code>Variant</code> is a special type in Pascal that underneath can hold values of various types. Moreover, operators are defined to allow operating on them and converting their values at run-time.</p>\n<p>The effect is a bit similar to scripting programming languages with dynamic typing.</p>\n<p>Do not use them without consideration: things are a bit less safe (you don&#39;t control types, conversions happen implicitly). Also there&#39;s a small performance hit, since all operations need to check and synchronize the types at run-time.</p>\n<p>But sometimes it does make sense. Namely, when you have to process data that intrinsically indeed may have different types, and you only know those types at runtime. E.g. when you want to process result of SQL <code>select * from some_table</code> in a generic database viewer (not knowing table structure at compile-time).</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/variant_types.dpr[]</p>\n<hr />\n<p>NOTE: Technically, <code>Variant</code> is realized using <code>TVarData</code> internal type, which is a record with variants. So these concepts are connected. But you should <em>not need to know this</em>, you should not use <code>TVarData</code> explicitly.</p>\n<h4 id=\"tvarrec-in-array-of-const\">TVarRec in array of const</h4>\n<p>When you use <code>array of const</code> special parameter type, it is passed as an array of <code>TVarRec</code>. See</p>\n<ul><li><code>TVarRec</code> in FPC: <a href=\"https://www.freepascal.org/docs-html/rtl/system/tvarrec.html\" rel=\"nofollow ugc noopener\">https://www.freepascal.org/docs-html/rtl/system/tvarrec.html</a></li><li><code>TVarRec</code> in Delphi: <a href=\"https://docwiki.embarcadero.com/Libraries/Sydney/en/System.TVarRec\" rel=\"nofollow ugc noopener\">https://docwiki.embarcadero.com/Libraries/Sydney/en/System.TVarRec</a></li></ul>\n<p>This is useful to pass to a routine parameters of arbitrary (not known at compile-time) types. For example, to implement routines like standard <code>Format</code> (similar to <code>sprintf</code> in C) or <em>Castle Game Game</em> <code>WriteLnLog</code> / <code>WriteLnWarning</code>.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/array_of_const.dpr[]</p>\n<hr />\n<h3 id=\"old-style-objects\">Old-style objects</h3>\n<p>In the old days, Turbo Pascal introduced another syntax for class-like functionality, using the <code>object</code> keyword. It&#39;s somewhat of a blend between the concept of a <code>record</code> and a modern <code>class</code>.</p>\n<ul><li>The old-style objects can be allocated / freed, and during that operation you can call their constructor / destructor.</li><li><p>But they can also be simply declared and used, like records. A simple <code>record</code> or <code>object</code> type is not a reference (pointer) to something, it&#39;s simply the data. This makes them comfortable for small data, where calling allocation / free would be bothersome.</p><p>//It also makes them fast -- a list of such structures is nicely linear in memory, iterating over it doesn&#39;t involve jumping over pointers. Also, their memory layout is defined in <em>some</em> situations (packed records, or records with C layout), which makes them suitable to pass to external APIs, like OpenGL.</p></li><li>Old-style objects offer inheritance and virtual methods, although with small differences from the modern classes. Be careful -- <em>bad things</em> will happen if you try to use an object without calling its constructor, and the object has virtual methods.</li></ul>\n<p>It&#39;s discouraged to use the old-style objects in most cases. Modern <em>classes</em> provide much more functionality. And when needed, records (including <em>advanced records</em>) can be used for performance. These concepts are usually a better idea than old-style objects.</p>\n<h3 id=\"pointers\">Pointers</h3>\n<p>You can create a <em>pointer</em> to any other type. The pointer to type <code>TMyRecord</code> is declared as <code>^TMyRecord</code>, and by convention is called <code>PMyRecord</code>. This is a traditional example of a linked list of integers using records:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>type\n  PMyRecord = ^TMyRecord;\n  TMyRecord = record\n    Value: Integer;\n    Next: PMyRecord;\n  end;</p>\n<hr />\n<p>Note that the definition is recursive (type <code>PMyRecord</code> is defined using type <code>TMyRecord</code>, while <code>TMyRecord</code> is defined using <code>PMyRecord</code>). It is allowed to define a pointer type to a <em>not-yet-defined type</em>, as long as it will be resolved within the same <code>type</code> block.</p>\n<p>You can allocate and free pointers using the <code>New</code> / <code>Dispose</code> methods, or (more low-level, not type-safe) <code>GetMem</code> / <code>FreeMem</code> methods. You dereference the pointer (to access the stuff <em>pointed by</em>) you append the <code>^</code> operator (e.g. <code>MyInteger := MyPointerToInteger^</code>). To make the inverse operation, which is to <em>get a pointer of an existing variable</em>, you prefix it with <code>@</code> operator (e.g. <code>MyPointerToInteger := @MyInteger</code>).</p>\n<p>There is also an untyped <code>Pointer</code> type, similar to <code>void*</code> in C-like languages. It is completely unsafe, and can be typecasted to any other pointer type.</p>\n<p>Remember that a <em>class instance</em> is also in fact a pointer, although it doesn&#39;t require any <code>^</code> or <code>@</code> operators to use it.\n//That&#39;s why it&#39;s called a <em>reference</em>.\nA linked list using classes is certainly possible, it would simply be this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>type\n  TMyClass = class\n    Value: Integer;\n    Next: TMyClass;\n  end;</p>\n<hr />\n<h3 id=\"operator-overloading\">Operator overloading</h3>\n<p>You can override the meaning of many language operators, for example to allow addition and multiplication of your custom types.</p>\n<p>Both FPC and Delphi support overloading operators by defining <code>class operator</code> methods inside advanced records. Like this:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/operator_overloading_class_operator.dpr[]</p>\n<hr />\n<p>NOTE: With FPC, make sure to tell the compiler you use the &quot;advanced records&quot; feature by <code>{$modeswitch advancedrecords}</code>.</p>\n<p>Take a look at the documentation to learn all possible operators that can be overloaded:</p>\n<ul><li><a href=\"https://wiki.freepascal.org/Operator_overloading[FPC\" rel=\"nofollow ugc noopener\">https://wiki.freepascal.org/Operator_overloading[FPC</a> operator overloading]</li><li><a href=\"https://docwiki.embarcadero.com/RADStudio/Sydney/en/Operator_Overloading_%28Delphi%29[Delphi\" rel=\"nofollow ugc noopener\">https://docwiki.embarcadero.com/RADStudio/Sydney/en/Operator_Overloading_%28Delphi%29[Delphi</a> operator overloading]</li></ul>\n<p>FPC supports also an alternative syntax to overload operators, by defining a global function like <code>operator*</code>. For example:</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/operator_overloading.dpr[]</p>\n<hr />\n<p>This approach (global <code>operator</code> functions) can be used to define operators on classes too. Since you usually create new instances of your classes inside the operator function, the caller must remember to free the result.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/operator_overloading_classes.dpr[]</p>\n<hr />\n<p>You can override operators on records too using the global <code>operator</code> functions. This is usually easier than overloading them for classes, as the caller doesn&#39;t have to deal then with memory management.</p>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/operator_overloading_records.dpr[]</p>\n<hr />\n<p>However, for records, we don&#39;t advise to use the global <code>operator</code> functions. Instead, use <code>{$modeswitch advancedrecords}</code> and override operators as <code>class operator</code> inside the record. Reasons:</p>\n<ul><li>This is compatible with Delphi.</li><li>This allows to use generic classes that depend on some operator&#39;s existence (like <code>TFPGList</code>, that depends on the equality operator being available) with such records. Otherwise the &quot;global&quot; definition of an operator (not inside the record) would not be found (because it&#39;s not available at the code that implements the <code>TFPGList</code>), and you could not specialize a list like <code>specialize TFPGList&lt;TMyRecord&gt;</code>.</li></ul>\n<p>[source,pascal]</p>\n<hr />\n<p>include::modern_pascal_code_samples/operator_overloading_records_lists.dpr[]</p>\n<hr />\n<p><em>(Tutorial continues at the canonical URL; extract truncated for length.)</em></p>","headings":[{"level":1,"text":"Modern Object Pascal Introduction for Programmers","id":"modern-object-pascal-introduction-for-programmers"},{"level":2,"text":"Why this book","id":"why-this-book"},{"level":2,"text":"Basics","id":"basics"},{"level":3,"text":"\"Hello world\" program","id":"hello-world-program"},{"level":3,"text":"Compilers and FPC \"syntax modes\"","id":"compilers-and-fpc-syntax-modes"},{"level":3,"text":"Functions, procedures, primitive types","id":"functions-procedures-primitive-types"},{"level":3,"text":"Testing (if)","id":"testing-if"},{"level":3,"text":"Logical, relational and bit-wise operators","id":"logical-relational-and-bit-wise-operators"},{"level":3,"text":"Testing single expression for multiple values (case)","id":"testing-single-expression-for-multiple-values-case"},{"level":3,"text":"Enumerated and ordinal types and sets and constant-length arrays","id":"enumerated-and-ordinal-types-and-sets-and-constant-length-arrays"},{"level":3,"text":"Loops (for, while, repeat, for .. in)","id":"loops-for-while-repeat-for-in"},{"level":3,"text":"Output, logging","id":"output-logging"},{"level":3,"text":"Converting to a string","id":"converting-to-a-string"},{"level":2,"text":"Units","id":"units"},{"level":3,"text":"Overview","id":"overview"},{"level":3,"text":"Extensions used for units and programs","id":"extensions-used-for-units-and-programs"},{"level":3,"text":"Initialization and finalization","id":"initialization-and-finalization"},{"level":3,"text":"Units using each other","id":"units-using-each-other"},{"level":3,"text":"Qualifying identifiers with unit name","id":"qualifying-identifiers-with-unit-name"},{"level":3,"text":"Exposing one unit identifiers from another","id":"exposing-one-unit-identifiers-from-another"},{"level":2,"text":"Classes","id":"classes"},{"level":3,"text":"Basics","id":"basics-2"},{"level":3,"text":"Inheritance, virtual methods, override, reintroduce","id":"inheritance-virtual-methods-override-reintroduce"},{"level":3,"text":"Classes and class instances, constructors, destructors","id":"classes-and-class-instances-constructors-destructors"},{"level":3,"text":"Testing class (is), typecasting (as, TMyClass(X))","id":"testing-class-is-typecasting-as-tmyclass-x"},{"level":3,"text":"Properties","id":"properties"},{"level":3,"text":"Exceptions - Quick Example","id":"exceptions-quick-example"},{"level":3,"text":"Visibility specifiers","id":"visibility-specifiers"},{"level":3,"text":"Default ancestor","id":"default-ancestor"},{"level":3,"text":"Self","id":"self"},{"level":3,"text":"Calling inherited method","id":"calling-inherited-method"},{"level":3,"text":"Virtual methods, override and reintroduce","id":"virtual-methods-override-and-reintroduce"},{"level":2,"text":"Freeing classes","id":"freeing-classes"},{"level":3,"text":"Remember to free the class instances","id":"remember-to-free-the-class-instances"},{"level":3,"text":"How to free","id":"how-to-free"},{"level":3,"text":"Manual and automatic freeing","id":"manual-and-automatic-freeing"},{"level":3,"text":"The virtual destructor called Destroy","id":"the-virtual-destructor-called-destroy"},{"level":3,"text":"Free notification","id":"free-notification"},{"level":3,"text":"Free notification observer (Castle Game Engine)","id":"free-notification-observer-castle-game-engine"},{"level":2,"text":"Exceptions","id":"exceptions"},{"level":3,"text":"Overview","id":"overview-2"},{"level":3,"text":"Raising","id":"raising"},{"level":3,"text":"Catching","id":"catching"},{"level":3,"text":"Finally (doing things regardless of whether an exception occurred)","id":"finally-doing-things-regardless-of-whether-an-exception-occurred"},{"level":3,"text":"How the exceptions are displayed by various libraries","id":"how-the-exceptions-are-displayed-by-various-libraries"},{"level":2,"text":"Run-time library","id":"run-time-library"},{"level":3,"text":"Input/output using streams","id":"input-output-using-streams"},{"level":3,"text":"Containers (lists, dictionaries) using generics","id":"containers-lists-dictionaries-using-generics"},{"level":3,"text":"Cloning: TPersistent.Assign","id":"cloning-tpersistent-assign"},{"level":2,"text":"Various language features","id":"various-language-features"},{"level":3,"text":"Local (nested) routines","id":"local-nested-routines"},{"level":3,"text":"Callbacks (aka events, aka pointers to functions, aka procedural variables)","id":"callbacks-aka-events-aka-pointers-to-functions-aka-procedural-va"},{"level":3,"text":"Anonymous functions","id":"anonymous-functions"},{"level":3,"text":"Generics","id":"generics"},{"level":3,"text":"Overloading","id":"overloading"},{"level":3,"text":"Preprocessor","id":"preprocessor"},{"level":3,"text":"Records","id":"records"},{"level":3,"text":"Variant records and related concepts","id":"variant-records-and-related-concepts"},{"level":3,"text":"Old-style objects","id":"old-style-objects"},{"level":3,"text":"Pointers","id":"pointers"},{"level":3,"text":"Operator overloading","id":"operator-overloading"}]}}