File size: 165,664 Bytes
08c8a6d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 |
Modern Object Pascal Introduction for
Programmers
Michalis Kamburelis
Table of Contents
1. Why ....................................................................................................................... 3
2. Basics .................................................................................................................... 4
2.1. "Hello world" program ................................................................................. 4
2.2. Functions, procedures, primitive types ....................................................... 4
2.3. Testing (if) ................................................................................................... 7
2.4. Logical, relational and bit-wise operators ................................................... 8
2.5. Testing single expression for multiple values (case) ................................... 9
2.6. Enumerated and ordinal types and sets and constant-length arrays ......... 10
2.7. Loops (for, while, repeat, for .. in) ............................................................ 11
2.8. Output, logging ......................................................................................... 14
2.9. Converting to a string ............................................................................... 15
3. Units .................................................................................................................... 16
3.1. Units using each other .............................................................................. 18
3.2. Qualifying identifiers with unit name ......................................................... 19
3.3. Exposing one unit identifiers from another ............................................... 22
4. Classes ............................................................................................................... 23
4.1. Basics ....................................................................................................... 23
4.2. Inheritance, is, as ..................................................................................... 24
4.3. Properties .................................................................................................. 26
4.4. Exceptions - Quick Example ..................................................................... 29
4.5. Visibility specifiers ..................................................................................... 30
4.6. Default ancestor ........................................................................................ 31
4.7. Self ............................................................................................................ 31
4.8. Calling inherited method ........................................................................... 31
4.9. Virtual methods, override and reintroduce ................................................ 35
5. Freeing classes ................................................................................................... 38
5.1. Remember to free the class instances ..................................................... 38
5.2. How to free ............................................................................................... 38
5.3. Manual and automatic freeing .................................................................. 40
5.4. The virtual destructor called Destroy ........................................................ 43
1
Modern Object Pascal Introduction for Programmers
5.5. Free notification ........................................................................................ 44
5.6. Free notification observer (Castle Game Engine) ..................................... 47
6. Exceptions ........................................................................................................... 48
6.1. Overview ................................................................................................... 48
6.2. Raising ...................................................................................................... 49
6.3. Catching .................................................................................................... 50
6.4. Finally (doing things regardless if an exception occurred) ........................ 53
6.5. How the exceptions are displayed by various libraries ............................. 57
7. Run-time library ................................................................................................... 57
7.1. Input/output using streams ....................................................................... 57
7.2. Containers (lists, dictionaries) using generics ........................................... 59
7.3. Cloning: TPersistent.Assign ...................................................................... 64
8. Various language features .................................................................................. 69
8.1. Local (nested) routines ............................................................................. 69
8.2. Callbacks (aka events, aka pointers to functions, aka procedural
variables) .......................................................................................................... 70
8.3. Generics .................................................................................................... 73
8.4. Overloading ............................................................................................... 75
8.5. Preprocessor ............................................................................................. 75
8.6. Records ..................................................................................................... 78
8.7. Old-style objects ....................................................................................... 79
8.8. Pointers ..................................................................................................... 80
8.9. Operator overloading ................................................................................ 81
9. Advanced classes features ................................................................................. 84
9.1. Private and strict private ........................................................................... 84
9.2. More stuff inside classes and nested classes ........................................... 84
9.3. Class methods .......................................................................................... 85
9.4. Class references ....................................................................................... 86
9.5. Static class methods ................................................................................. 89
9.6. Class properties and variables ................................................................. 90
9.7. Class helpers ............................................................................................ 91
9.8. Virtual constructors, destructors ............................................................... 93
9.9. An exception in constructor ...................................................................... 93
10. Interfaces .......................................................................................................... 95
10.1. Bare (CORBA) interfaces ....................................................................... 95
10.2. CORBA and COM types of interfaces .................................................... 97
10.3. Interfaces GUIDs .................................................................................... 99
10.4. Reference-counted (COM) interfaces ..................................................... 99
2
Modern Object Pascal Introduction for Programmers
10.5. Using COM interfaces with reference-counting disabled ....................... 102
10.6. Typecasting interfaces .......................................................................... 104
11. About this document ....................................................................................... 107
1. Why
There are many books and resources about Pascal out there, but too many of them
talk about the old Pascal, without classes, units or generics.
So I wrote this quick introduction to what I call modern Object Pascal. Most of the
programmers using it don’t really call it "modern Object Pascal", we just call it "our
Pascal". But when introducing the language, I feel it’s important to emphasize that it’s
a modern, object-oriented language. It evolved a lot since the old (Turbo) Pascal that
many people learned in schools long time ago. Feature-wise, it’s quite similar to C+
+ or Java or C#.
• It has all the modern features you expect — classes, units, interfaces, generics…
• It’s compiled to a fast, native code,
• It’s very type safe,
• High-level but can also be low-level if you need it to be.
It also has excellent, portable and open-source compiler called the Free Pascal
Compiler, http://freepascal.org/ . And an accompanying IDE (editor, debugger, a library
of visual components, form designer) called Lazarus http://lazarus.freepascal.org/
. There’s also a proprietary and commercial compiler and IDE Delphi https://
www.embarcadero.com/products/Delphi . There’s a lot of libraries (for both FPC
and Delphi) available, see https://github.com/Fr0sT-Brutal/awesome-pascal . We also
support existing editors like VS Code, see https://castle-engine.io/vscode . 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, macOS, Android, iOS, Nintendo Switch; also WebGL is coming).
This introduction is mostly directed at programmers who already have experience in
other languages. We will not cover here the meanings of some universal concepts, like
"what is a class", we’ll only show how to do them in Pascal.
3
Modern Object Pascal Introduction for Programmers
2. Basics
2.1. "Hello world" program
{$mode objfpc}{$H+}{$J-} // Just use this line in all modern sources
program MyProgram; // Save this file as myprogram.lpr
begin
WriteLn('Hello world!');
end.
This is a complete program that you can compile and run.
• If you use the command-line FPC, just create a new file myprogram.lpr and
execute fpc myprogram.lpr .
• If you use Lazarus, create a new project (menu Project → New Project → Simple
Program). Save it as myprogram and paste this source code as the main file.
Compile using the menu item Run # Compile.
• This is a command-line program, so in either case — just run the compiled
executable from the command-line.
The 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).
Voila — a working GUI application, cross-platform, with native look everywhere, using
a comfortable visual component library. The Lazarus and Free Pascal Compiler come
with lots of ready 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:)
2.2. Functions, procedures, primitive types
{$mode objfpc}{$H+}{$J-}
program MyProgram;
procedure MyProcedure(const A: Integer);
begin
WriteLn('A + 10 is: ', A + 10);
4
Modern Object Pascal Introduction for Programmers
end;
function MyFunction(const S: string): string;
begin
Result := S + 'strings are automatically managed';
end;
var
X: Single;
begin
WriteLn(MyFunction('Note: '));
MyProcedure(5);
// Division using "/" always makes float result, use "div" for integer
division
X := 15 / 5;
WriteLn('X is now: ', X); // scientific notation
WriteLn('X is now: ', X:1:2); // 2 decimal places
end.
To 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.
function MyFunction(const S: string): string;
begin
Result := S + 'something';
Result := Result + ' something more!';
Result := Result + ' and more!';
end;
You 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.
If 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:
function SumIntegersUntilZero: Integer;
5
Modern Object Pascal Introduction for Programmers
var
I: Integer;
begin
Readln(I);
Result := I;
if I <> 0 then
Result := Result + SumIntegersUntilZero();
end;
You 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.
function AddName(const ExistingNames, NewName: string): string;
begin
if ExistingNames = '' then
Exit(NewName);
Result := ExistingNames + ', ' + NewName;
end;
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 side effect (e.g. it modifies a
global variable) besides calculating the result. For example:
var
Count: Integer;
MyCount: Integer;
function CountMe: Integer;
begin
Inc(Count);
Result := Count;
end;
begin
Count := 10;
CountMe; // the function result is discarded, but the function is
executed, Count is now 11
MyCount := CountMe; // use the result of the function, MyCount equals to
Count which is now 12
end.
6
Modern Object Pascal Introduction for Programmers
2.3. Testing (if)
Use 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.
var
A: Integer;
B: boolean;
begin
if A > 0 then
DoSomething;
if A > 0 then
begin
DoSomething;
AndDoSomethingMore;
end;
if A > 10 then
DoSomething
else
DoSomethingElse;
// equivalent to above
B := A > 10;
if B then
DoSomething
else
DoSomethingElse;
end;
The else is paired with the last if . So this works as you expect:
if A <> 0 then
if B <> 0 then
AIsNonzeroAndBToo
else
AIsNonzeroButBIsZero;
While 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.
7
Modern Object Pascal Introduction for Programmers
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.
if A <> 0 then
begin
if B <> 0 then
AIsNonzeroAndBToo
else
AIsNonzeroButBIsZero;
end;
2.4. Logical, relational and bit-wise operators
The 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.
The 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 := .
The 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.
For example this is a compilation error:
var
A, B: Integer;
begin
if A = 0 and B <> 0 then ... // INCORRECT example
The 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 .
This is correct:
8
Modern Object Pascal Introduction for Programmers
var
A, B: Integer;
begin
if (A = 0) and (B <> 0) then ...
The short-circuit evaluation is used. Consider this expression:
if MyFunction(X) and MyOtherFunction(Y) then...
• It’s guaranteed that MyFunction(X) will be evaluated first.
• 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.
• 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.
• This is particularly useful when writing expressions like
if (A <> nil) and A.IsValid then...
This 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.
2.5. Testing single expression for multiple values (case)
If a different action should be executed depending on the value of some expression,
then the case .. of .. end statement is useful.
case SomeValue of
0: DoSomething;
1: DoSomethingElse;
2: begin
IfItsTwoThenDoThis;
AndAlsoDoThis;
end;
3..10: DoSomethingInCaseItsInThisRange;
11, 21, 31: AndDoSomethingForTheseSpecialValues;
else DoSomethingInCaseOfUnexpectedValue;
end;
9
Modern Object Pascal Introduction for Programmers
The else clause is optional (and corresponds to default in C-like languages).
When no condition matches, and there’s no else , then nothing happens.
In 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.
2.6. Enumerated and ordinal types and sets and constant-length
arrays
Enumerated type in Pascal is a very nice, opaque type. You will probably use it much
more often than enums in other languages:)
type
TAnimalKind = (akDuck, akCat, akDog);
The 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.
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.
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.
The 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)) ).
Enumerated and ordinal types can be used as array indexes:
10
Modern Object Pascal Introduction for Programmers
type
TArrayOfTenStrings = array [0..9] of string;
TArrayOfTenStrings1Based = array [1..10] of string;
TMyNumber = 0..9;
TAlsoArrayOfTenStrings = array [TMyNumber] of string;
TAnimalKind = (akDuck, akCat, akDog);
TAnimalNames = array [TAnimalKind] of string;
They can also be used to create sets (a bit-fields internally):
type
TAnimalKind = (akDuck, akCat, akDog);
TAnimals = set of TAnimalKind;
var
A: TAnimals;
begin
A := [];
A := [akDuck, akCat];
A := A + [akDog];
A := A * [akCat, akDog];
Include(A, akDuck);
Exclude(A, akDuck);
end;
2.7. Loops (for, while, repeat, for .. in)
{$mode objfpc}{$H+}{$J-}
{$R+} // range checking on - nice for debugging
var
MyArray: array [0..9] of Integer;
I: Integer;
begin
// initialize
for I := 0 to 9 do
MyArray[I] := I * I;
// show
for I := 0 to 9 do
WriteLn('Square is ', MyArray[I]);
// does the same as above
11
Modern Object Pascal Introduction for Programmers
for I := Low(MyArray) to High(MyArray) do
WriteLn('Square is ', MyArray[I]);
// does the same as above
I := 0;
while I < 10 do
begin
WriteLn('Square is ', MyArray[I]);
I := I + 1; // or "I += 1", or "Inc(I)"
end;
// does the same as above
I := 0;
repeat
WriteLn('Square is ', MyArray[I]);
Inc(I);
until I = 10;
// does the same as above
// note: here I enumerates MyArray values, not indexes
for I in MyArray do
WriteLn('Square is ', I);
end.
About the repeat and while loops:
There are two differences between these loop types:
1. 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.
2. In case of repeat , the condition is not checked at the beginning. So the repeat
loop always runs at least once.
About the for I := … loops:
The 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.
In 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.
12
Modern Object Pascal Introduction for Programmers
Note 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.
About the for I in … loops:
The for I in .. do .. is similar to foreach construct in many modern
languages. It works intelligently on many built-in types:
• It can iterate over all values in the array (example above).
• It can iterate over all possible values of an enumerated type:
var
AK: TAnimalKind;
begin
for AK in TAnimalKind do...
• It can iterate over all items included in the set:
var
Animals: TAnimals;
AK: TAnimalKind;
begin
Animals := [akDog, akCat];
for AK in Animals do ...
• And it works on custom list types, generic or not, like TObjectList or
TFPGObjectList .
{$mode objfpc}{$H+}{$J-}
uses
SysUtils, FGL;
type
TMyClass = class
I, Square: Integer;
end;
TMyClassList = specialize TFPGObjectList<TMyClass>;
var
List: TMyClassList;
13
Modern Object Pascal Introduction for Programmers
C: TMyClass;
I: Integer;
begin
List := TMyClassList.Create(true); // true = owns children
try
for I := 0 to 9 do
begin
C := TMyClass.Create;
C.I := I;
C.Square := I * I;
List.Add(C);
end;
for C in List do
WriteLn('Square of ', C.I, ' is ', C.Square);
finally
FreeAndNil(List);
end;
end.
We 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:)
2.8. Output, logging
To simply output strings in Pascal, use the Write or WriteLn routine. The latter
automatically adds a newline at the end.
This 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.
WriteLn('Hello world!');
WriteLn('You can output an integer: ', 3 * 4);
WriteLn('You can pad an integer: ', 666:10);
WriteLn('You can output a float: ', Pi:1:4);
To 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
WriteLn('One line.\nSecond line.'); // INCORRECT example
14
Modern Object Pascal Introduction for Programmers
doesn’t work like some of you would think. This will work:
WriteLn('One line.' + LineEnding + 'Second line.');
or just this:
WriteLn('One line.');
WriteLn('Second line.');
Note 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).
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.
2.9. Converting to a string
To convert an arbitrary number of arguments to a string (instead of just directly
outputting them), you have a couple of options.
• 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) .
# Advantage: Absolutely flexible. There are many XxxToStr overloaded
versions and friends (like FormatFloat ), covering many types. Most of them
are in the SysUtils unit.
# 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 ).
15
Modern Object Pascal Introduction for Programmers
# Disadvantage: A long concatenation of many XxxToStr calls and strings
doesn’t look nice.
• 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.
# 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.
# 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.
# 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).
• WriteStr(TargetString, …) routine behaves much like Write(…) , except
that the result is saved to the TargetString .
# Advantage: It supports all the features of Write , including the special syntax
for formatting like Pi:1:4 .
# 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.
3. Units
Units 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
16
Modern Object Pascal Introduction for Programmers
for other units and programs, and then the implementation. Save unit MyUnit as
myunit.pas (lowercase with .pas extension).
{$mode objfpc}{$H+}{$J-}
unit MyUnit;
interface
procedure MyProcedure(const A: Integer);
function MyFunction(const S: string): string;
implementation
procedure MyProcedure(const A: Integer);
begin
WriteLn('A + 10 is: ', A + 10);
end;
function MyFunction(const S: string): string;
begin
Result := S + 'strings are automatically managed';
end;
end.
Final programs are saved as myprogram.lpr files ( lpr = Lazarus program file; in
Delphi you would use .dpr ). Note that other conventions are possible here, e.g. some
projects just use .pas for main program file, some use .pp for units or programs. I
advise using .pas for units and .lpr for FPC/Lazarus programs.
A program can use a unit by a uses keyword:
{$mode objfpc}{$H+}{$J-}
program MyProgram;
uses
MyUnit;
begin
WriteLn(MyFunction('Note: '));
MyProcedure(5);
end.
17
Modern Object Pascal Introduction for Programmers
A unit may also contain initialization and finalization sections. This is the
code executed when the program starts and ends.
{$mode objfpc}{$H+}{$J-}
unit initialization_finalization;
interface
implementation
initialization
WriteLn('Hello world!');
finalization
WriteLn('Goodbye world!');
end.
3.1. Units using each other
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’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).
{$mode objfpc}{$H+}{$J-}
unit AnotherUnit;
interface
uses
Classes;
{ The "TComponent" type (class) is defined in the Classes unit.
That's why we had to use the Classes unit above. }
procedure DoSomethingWithComponent(var C: TComponent);
implementation
uses SysUtils;
procedure DoSomethingWithComponent(var C: TComponent);
begin
{ The FreeAndNil procedure is defined in the SysUtils unit.
Since we only refer to its name in the implementation,
it was OK to use the SysUtils unit in the "implementation" section. }
18
Modern Object Pascal Introduction for Programmers
FreeAndNil(C);
end;
end.
It is not allowed to have circular unit dependencies in the interface. That is, two
units cannot use each other in the interface section. The reason is that in order to
"understand" the 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.
It 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.
3.2. Qualifying identifiers with unit name
Different 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. In 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.
You 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.
{$mode objfpc}{$H+}{$J-}
program showcolor;
// Both Graphics and GoogleMapsEngine units define TColor type.
uses Graphics, GoogleMapsEngine;
var
{ This doesn't work like we want, as TColor ends up
being defined by GoogleMapsEngine. }
// Color: TColor;
19
Modern Object Pascal Introduction for Programmers
{ This works Ok. }
Color: Graphics.TColor;
begin
Color := clYellow;
WriteLn(Red(Color), ' ', Green(Color), ' ', Blue(Color));
end.
In 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:
{$mode objfpc}{$H+}{$J-}
unit UnitUsingColors;
// INCORRECT example
interface
uses Graphics;
procedure ShowColor(const Color: TColor);
implementation
uses GoogleMapsEngine;
procedure ShowColor(const Color: TColor);
begin
// WriteLn(ColorToString(Color));
end;
end.
The 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
20
Modern Object Pascal Introduction for Programmers
implementation. The equivalent version of the above unit, where the error is obvious,
looks like this:
{$mode objfpc}{$H+}{$J-}
unit UnitUsingColors;
// INCORRECT example.
// This is what the compiler "sees" when trying to compile previous
example
interface
uses Graphics;
procedure ShowColor(const Color: Graphics.TColor);
implementation
uses GoogleMapsEngine;
procedure ShowColor(const Color: GoogleMapsEngine.TColor);
begin
// WriteLn(ColorToString(Color));
end;
end.
The 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.
{$mode objfpc}{$H+}{$J-}
unit UnitUsingColors;
interface
uses Graphics;
procedure ShowColor(const Color: TColor);
implementation
21
Modern Object Pascal Introduction for Programmers
uses GoogleMapsEngine;
procedure ShowColor(const Color: Graphics.TColor);
begin
// WriteLn(ColorToString(Color));
end;
end.
3.3. Exposing one unit identifiers from another
Sometimes 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.
Sometimes this is necessary to preserve backward compatibility with previous unit
versions. Sometimes it’s nice to "hide" an internal unit this way.
This can be done by redefining the identifier in your new unit.
{$mode objfpc}{$H+}{$J-}
unit MyUnit;
interface
uses Graphics;
type
{ Expose TColor from Graphics unit as TMyColor. }
TMyColor = TColor;
{ Alternatively, expose it under the same name.
Qualify with unit name in this case, otherwise
we would refer to ourselves with "TColor = TColor" definition. }
TColor = Graphics.TColor;
const
{ This works with constants too. }
clYellow = Graphics.clYellow;
clBlue = Graphics.clBlue;
implementation
22
Modern Object Pascal Introduction for Programmers
end.
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 Section 8.2, “Callbacks (aka events, aka pointers to
functions, aka procedural variables)”), but that looks quite dirty.
The usual solution is then to create a trivial "wrapper" functions that underneath simply
call the functions from the internal unit, passing the parameters and return values
around.
To make this work with global variables, one can use global (unit-level) properties, see
Section 4.3, “Properties”.
4. Classes
4.1. Basics
We have classes. At the basic level, a class is just a container for
• fields (which is fancy name for "a variable inside a class"),
• methods (which is fancy name for "a procedure or function inside a class"),
• 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 Section 4.3, “Properties”).
• Actually, there are more possibilities, described in Section 9.2, “More stuff inside
classes and nested classes”.
type
TMyClass = class
MyInt: Integer; // this is a field
property MyIntProperty: Integer read MyInt write MyInt; // this is a
property
procedure MyMethod; // this is a method
end;
procedure TMyClass.MyMethod;
begin
WriteLn(MyInt + 10);
end;
23
Modern Object Pascal Introduction for Programmers
4.2. Inheritance, is, as
We have inheritance and virtual methods.
{$mode objfpc}{$H+}{$J-}
program MyProgram;
uses
SysUtils;
type
TMyClass = class
MyInt: Integer;
procedure MyVirtualMethod; virtual;
end;
TMyClassDescendant = class(TMyClass)
procedure MyVirtualMethod; override;
end;
procedure TMyClass.MyVirtualMethod;
begin
WriteLn('TMyClass shows MyInt + 10: ', MyInt + 10);
end;
procedure TMyClassDescendant.MyVirtualMethod;
begin
WriteLn('TMyClassDescendant shows MyInt + 20: ', MyInt + 20);
end;
var
C: TMyClass;
begin
C := TMyClass.Create;
try
C.MyVirtualMethod;
finally
FreeAndNil(C);
end;
C := TMyClassDescendant.Create;
try
C.MyVirtualMethod;
finally
FreeAndNil(C);
24
Modern Object Pascal Introduction for Programmers
end;
end.
By default methods are not virtual, declare them with virtual to make them.
Overrides must be marked with override , otherwise you will get a warning. To hide
a method without overriding (usually you don’t want to do this, unless you now what
you’re doing) use reintroduce .
To test the class of an instance at runtime, use the is operator. To typecast the
instance to a specific class, use the as operator.
{$mode objfpc}{$H+}{$J-}
program is_as;
uses
SysUtils;
type
TMyClass = class
procedure MyMethod;
end;
TMyClassDescendant = class(TMyClass)
procedure MyMethodInDescendant;
end;
procedure TMyClass.MyMethod;
begin
WriteLn('MyMethod');
end;
procedure TMyClassDescendant.MyMethodInDescendant;
begin
WriteLn('MyMethodInDescendant');
end;
var
Descendant: TMyClassDescendant;
C: TMyClass;
begin
Descendant := TMyClassDescendant.Create;
try
Descendant.MyMethod;
Descendant.MyMethodInDescendant;
25
Modern Object Pascal Introduction for Programmers
{ Descendant has all functionality expected of
the TMyClass, so this assignment is OK }
C := Descendant;
C.MyMethod;
{ this cannot work, since TMyClass doesn't define this method }
//C.MyMethodInDescendant;
if C is TMyClassDescendant then
(C as TMyClassDescendant).MyMethodInDescendant;
finally
FreeAndNil(Descendant);
end;
end.
Instead 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 :
if A is TMyClass then
(A as TMyClass).CallSomeMethodOfMyClass;
// below is marginally faster
if A is TMyClass then
TMyClass(A).CallSomeMethodOfMyClass;
4.3. Properties
Properties are a very nice "syntax sugar" to
1. 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.
2. Make something that looks like a field, but is read-only. In effect, it’s like a constant
or a parameter-less function.
type
TWebPage = class
private
26
Modern Object Pascal Introduction for Programmers
FURL: string;
FColor: TColor;
function SetColor(const Value: TColor);
public
{ No way to set it directly.
Call the Load method, like Load('http://www.freepascal.org/'),
to load a page and set this property. }
property URL: string read FURL;
procedure Load(const AnURL: string);
property Color: TColor read FColor write SetColor;
end;
procedure TWebPage.Load(const AnURL: string);
begin
FURL := AnURL;
NetworkingComponent.LoadWebPage(AnURL);
end;
function TWebPage.SetColor(const Value: TColor);
begin
if FColor <> Value then
begin
FColor := Value;
// for example, cause some update each time value changes
Repaint;
// as another example, make sure that some underlying instance,
// like a "RenderingComponent" (whatever that is),
// has a synchronized value of Color.
RenderingComponent.Color := Value;
end;
end;
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 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).
When declaring a property you specify:
1. Whether it can be read, and how (by directly reading a field, or by using a "getter"
method).
2. 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).
27
Modern Object Pascal Introduction for Programmers
The 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 .
Technically, 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:
• 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.
Note 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.
• 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 .
• 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.
• The "backing" field of a property is almost always private, since the idea of a property
is to encapsulate all outside access to it.
• It’s technically possible to make set-only properties, but I have not yet seen a good
example of such thing:)
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.
28
Modern Object Pascal Introduction for Programmers
Serialization of properties
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.
Serialization 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).
In the Castle Game Engine: Use the CastleComponentSerialize unit (based
on FpJsonRtti ) to serialize our user-interface and transformation component
hierarchies.
At each property, you can declare some additional things that will be helpful for any
serialization algorithm:
• 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".
• Whether the property should be stored at all (using the stored keyword).
4.4. Exceptions - Quick Example
We have exceptions. They can be caught with try … except … end clauses, and
we have finally sections like try … finally … end .
{$mode objfpc}{$H+}{$J-}
program MyProgram;
uses
SysUtils;
type
TMyClass = class
29
Modern Object Pascal Introduction for Programmers
procedure MyMethod;
end;
procedure TMyClass.MyMethod;
begin
if Random > 0.5 then
raise Exception.Create('Raising an exception!');
end;
var
C: TMyClass;
begin
Randomize;
C := TMyClass.Create;
try
C.MyMethod;
finally
FreeAndNil(C);
end;
end.
Note 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).
See the Section 6, “Exceptions” chapter for more in-depth description of exceptions.
4.5. Visibility specifiers
As in most object-oriented languages, we have visibility specifiers to hide fields /
methods / properties.
The basic visibility levels are:
public
everyone can access it, including the code in other units.
private
only accessible in this class.
protected
only accessible in this class and descendants.
The 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
30
Modern Object Pascal Introduction for Programmers
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 Section 9.1, “Private and strict private”.
By 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.
Not 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.
4.6. Default ancestor
If you don’t declare the ancestor type, every class inherits from TObject .
4.7. Self
The 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.
4.8. Calling inherited method
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, TMyClass2.MyOtherMethod
calls MyMethod , which ends up calling TMyClass2.MyMethod .
{$mode objfpc}{$H+}{$J-}
uses SysUtils;
type
TMyClass1 = class
procedure MyMethod;
end;
TMyClass2 = class(TMyClass1)
procedure MyMethod;
31
Modern Object Pascal Introduction for Programmers
procedure MyOtherMethod;
end;
procedure TMyClass1.MyMethod;
begin
Writeln('TMyClass1.MyMethod');
end;
procedure TMyClass2.MyMethod;
begin
Writeln('TMyClass2.MyMethod');
end;
procedure TMyClass2.MyOtherMethod;
begin
MyMethod; // this calls TMyClass2.MyMethod
end;
var
C: TMyClass2;
begin
C := TMyClass2.Create;
try
C.MyOtherMethod;
finally FreeAndNil(C) end;
end.
If 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
• The compiler looks for TMyClass2.MyMethod .
• If not found, it looks for TMyClass1.MyMethod .
• If not found, it looks for TObject.MyMethod .
• if not found, then the compilation fails.
test
it by commenting out
You can
the TMyClass2.MyMethod definition
in the example above. In effect, TMyClass1.MyMethod will be called by
TMyClass2.MyOtherMethod .
Sometimes, 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:
32
Modern Object Pascal Introduction for Programmers
inherited MyMethod;
This 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 .
ahead,
Go
TMyClass2.MyOtherMethod above
MyMethod , and see the difference in the output.
change
the
implementation
of
to use inherited
The 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.
{$mode objfpc}{$H+}{$J-}
uses SysUtils;
type
TMyClass1 = class
constructor Create;
procedure MyMethod(const A: Integer);
end;
TMyClass2 = class(TMyClass1)
constructor Create;
procedure MyMethod(const A: Integer);
end;
constructor TMyClass1.Create;
begin
inherited Create; // this calls TObject.Create
Writeln('TMyClass1.Create');
end;
procedure TMyClass1.MyMethod(const A: Integer);
begin
Writeln('TMyClass1.MyMethod ', A);
end;
constructor TMyClass2.Create;
begin
inherited Create; // this calls TMyClass1.Create
33
Modern Object Pascal Introduction for Programmers
Writeln('TMyClass2.Create');
end;
procedure TMyClass2.MyMethod(const A: Integer);
begin
inherited MyMethod(A); // this calls TMyClass1.MyMethod
Writeln('TMyClass2.MyMethod ', A);
end;
var
C: TMyClass2;
begin
C := TMyClass2.Create;
try
C.MyMethod(123);
finally FreeAndNil(C) end;
end.
Since using inherited to call a method with the same name, with the same
arguments, is a very often 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".
In the above example, all the inherited …; calls could be
replaced by a simple inherited; .
Note 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:
procedure TMyClass2.MyMethod(A: Integer);
begin
WriteLn('TMyClass2.MyMethod beginning ', A);
A := 456;
{ This calls TMyClass1.MyMethod with A = 456,
regardless of the A value passed to this method
(TMyClass2.MyMethod). }
inherited;
WriteLn('TMyClass2.MyMethod ending ', A);
end;
34
Modern Object Pascal Introduction for Programmers
Note 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 if 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 not virtual methods.
4.9. Virtual methods, override and reintroduce
By default, the methods are not virtual. This is similar to C++, and unlike Java.
When 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 .
The 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:
{$mode objfpc}{$H+}{$J-}
uses SysUtils;
type
TFruit = class
procedure Eat;
end;
TApple = class(TFruit)
procedure Eat;
end;
procedure TFruit.Eat;
begin
Writeln('Eating a fruit');
end;
procedure TApple.Eat;
begin
Writeln('Eating an apple');
end;
procedure DoSomethingWithAFruit(const Fruit: TFruit);
35
Modern Object Pascal Introduction for Programmers
begin
Writeln('We have a fruit with class ', Fruit.ClassName);
Writeln('We eat it:');
Fruit.Eat;
end;
var
Apple: TApple; // Note: you could as well declare "Apple: TFruit" here
begin
Apple := TApple.Create;
try
DoSomethingWithAFruit(Apple);
finally FreeAndNil(Apple) end;
end.
This example will print
We have a fruit with class TApple
We eat it:
Eating a fruit
In effect, the call Fruit.Eat called the TFruit.Eat implementation, and nothing
calls the TApple.Eat implementation.
If 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).
In other words, the method to be called is determined at compile-time.
Using 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.
In Object Pascal, to define a method as virtual, you need to
36
Modern Object Pascal Introduction for Programmers
• Mark its first definition (in the top-most ancestor) with the virtual keyword.
• 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).
{$mode objfpc}{$H+}{$J-}
uses SysUtils;
type
TFruit = class
procedure Eat; virtual;
end;
TApple = class(TFruit)
procedure Eat; override;
end;
procedure TFruit.Eat;
begin
Writeln('Eating a fruit');
end;
procedure TApple.Eat;
begin
Writeln('Eating an apple');
end;
procedure DoSomethingWithAFruit(const Fruit: TFruit);
begin
Writeln('We have a fruit with class ', Fruit.ClassName);
Writeln('We eat it:');
Fruit.Eat;
end;
var
Apple: TApple; // Note: you could as well declare "Apple: TFruit" here
begin
Apple := TApple.Create;
try
DoSomethingWithAFruit(Apple);
finally FreeAndNil(Apple) end;
end.
This example will print
37
Modern Object Pascal Introduction for Programmers
We have a fruit with class TApple
We eat it:
Eating an apple
Internally, 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.
If 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.
5. Freeing classes
5.1. Remember to free the class instances
The class instances have to be manually freed, otherwise you get memory leaks.
I advise using FPC -gl -gh options to detect memory leaks (see https://castle-
engine.io/manual_optimization.php#section_memory ).
Note that this doesn’t concern raised exceptions. Although you do create a class when
raising an exception (and it’s a perfectly normal class, and you can create your own
classes for this purpose too). But this class instance is freed automatically.
5.2. How to free
To 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.
It is more-or-less a shortcut for
if A <> nil then
begin
A.Destroy;
A := nil;
38
Modern Object Pascal Introduction for Programmers
end;
Actually, 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.
Often you will also see people using the A.Free method, which is like doing
if A <> nil then
A.Destroy;
This frees the A , unless it’s nil .
Note 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 .
This trick (officially allowing the method to be used with Self equal
nil ) is possible only in non-virtual methods.
In 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
method_with_self_nil.lpr 1.
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).
We advise using FreeAndNil(A) always, without exceptions, and never to call
directly the Free method or Destroy destructor.
The 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. But note that using
1
https://github.com/michaliskambi/modern-pascal-introduction/blob/master/code-samples/
method_with_self_nil.lpr
39
Modern Object Pascal Introduction for Programmers
FreeAndNil(A) doesn’t guarantee this assertion. 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.
A := TMyClass.Create;
B := A;
FreeAndNil(A);
// B now contains a dangling pointer
More about dealing with this in the later section about "Free notification".
Still, FreeAndNil(A) takes care of the most trivial cases, so it’s a good habit to use it
IMHO. You will appreciate it when debuggging some errors, it is nice to easily observe
" X is already freed, because X is nil now".
5.3. Manual and automatic freeing
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 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) .
So, like this:
uses SysUtils;
type
TGun = class
end;
TPlayer = class
Gun1, Gun2: TGun;
constructor Create;
destructor Destroy; override;
end;
constructor TPlayer.Create;
begin
inherited;
Gun1 := TGun.Create;
Gun2 := TGun.Create;
end;
40
Modern Object Pascal Introduction for Programmers
destructor TPlayer.Destroy;
begin
FreeAndNil(Gun1);
FreeAndNil(Gun2);
inherited;
end;
To 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:
uses SysUtils, Classes;
type
TGun = class(TComponent)
end;
TPlayer = class(TComponent)
Gun1, Gun2: TGun;
constructor Create(AOwner: TComponent); override;
end;
constructor TPlayer.Create(AOwner: TComponent);
begin
inherited;
Gun1 := TGun.Create(Self);
Gun2 := TGun.Create(Self);
end;
Note 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.)
Note 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); .
41
Modern Object Pascal Introduction for Programmers
Another mechanism for automatic freeing is the OwnsObjects functionality (by
default already true !) of list-classes like TFPGObjectList or TObjectList . So
we can also write:
uses SysUtils, Classes, FGL;
type
TGun = class
end;
TGunList = specialize TFPGObjectList<TGun>;
TPlayer = class
Guns: TGunList;
Gun1, Gun2: TGun;
constructor Create;
destructor Destroy; override;
end;
constructor TPlayer.Create;
begin
inherited;
// Actually, the parameter true (OwnsObjects) is already the default
Guns := TGunList.Create(true);
Gun1 := TGun.Create;
Guns.Add(Gun1);
Gun2 := TGun.Create;
Guns.Add(Gun2);
end;
destructor TPlayer.Destroy;
begin
{ We have to take care to free the list.
It will automatically free its contents. }
FreeAndNil(Guns);
{ No need to free the Gun1, Gun2 anymore. It's a nice habit to set to
"nil"
their references now, as we know they are freed. In this simple class,
with so simple destructor, it's obvious that they cannot be accessed
anymore -- but doing this pays off in case of larger and more
complicated
destructors.
Alternatively, we could avoid declaring Gun1 and Gun2,
42
Modern Object Pascal Introduction for Programmers
and instead use Guns[0] and Guns[1] in own code.
Or create a method like Gun1 that returns Guns[0]. }
Gun1 := nil;
Gun2 := nil;
inherited;
end;
Beware 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.
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 .
5.4. The virtual destructor called Destroy
As you saw in the examples above, when the class is destroyed, its destructor
called Destroy is called.
In 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.
The 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 Section 4.9, “Virtual methods, override
and reintroduce”.
This information about destructors is, indeed, inconsistent with the
constructors.
It’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.
Also, the Create constructor in the TObject is not virtual, so you
do not mark it with override in the descendants.
43
Modern Object Pascal Introduction for Programmers
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’re
not forced to do it.
Note, 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.
5.5. Free notification
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 "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).
Using 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:
var
Obj1, Obj2: TObject;
begin
Obj1 := TObject.Create;
Obj2 := Obj1;
FreeAndNil(Obj1);
// what happens if we access Obj1 or Obj2 here?
end;
44
Modern Object Pascal Introduction for Programmers
1. 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
if Obj1 <> nil then
WriteLn(Obj1.ClassName);
Trying 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.
Same goes for calling a virtual method, or calling a non-virtual method that
accessed a field of a nil instance.
2. 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 results in an unpredictable
behavior — maybe an access violation exception, maybe a garbage data returned.
There are various solutions to it:
• 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.
• 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.
• 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 .
Thus you get something like a weak reference. It can cope with various usage
scenarios, for example you can let the code from outside of the class to set your
reference, and the outside code can also free the instance at anytime.
This requires both classes to descend from TComponent . Using it in general
boils down to calling FreeNotification , RemoveFreeNotification , and
overriding Notification .
45
Modern Object Pascal Introduction for Programmers
Here’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:)
type
TControl = class(TComponent)
end;
TContainer = class(TComponent)
private
FSomeSpecialControl: TControl;
procedure SetSomeSpecialControl(const Value: TControl);
protected
procedure Notification(AComponent: TComponent; Operation:
TOperation); override;
public
destructor Destroy; override;
property SomeSpecialControl: TControl
read FSomeSpecialControl write SetSomeSpecialControl;
end;
implementation
procedure TContainer.Notification(AComponent: TComponent; Operation:
TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FSomeSpecialControl) then
{ set to nil by SetSomeSpecialControl to clean nicely }
SomeSpecialControl := nil;
end;
procedure TContainer.SetSomeSpecialControl(const Value: TControl);
begin
if FSomeSpecialControl <> Value then
begin
if FSomeSpecialControl <> nil then
FSomeSpecialControl.RemoveFreeNotification(Self);
FSomeSpecialControl := Value;
if FSomeSpecialControl <> nil then
FSomeSpecialControl.FreeNotification(Self);
end;
end;
46
Modern Object Pascal Introduction for Programmers
destructor TContainer.Destroy;
begin
{ set to nil by SetSomeSpecialControl, to detach free notification }
SomeSpecialControl := nil;
inherited;
end;
5.6. Free notification observer (Castle Game Engine)
In Castle Game Engine we encourage to use TFreeNotificationObserver
from CastleClassUtils unit instead of directly calling FreeNotification ,
RemoveFreeNotification and overriding Notification .
In 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).
This is the example code using TFreeNotificationObserver , to achieve the
same effect as example in the previous section:
type
TControl = class(TComponent)
end;
TContainer = class(TComponent)
private
FSomeSpecialControlObserver: TFreeNotificationObserver;
FSomeSpecialControl: TControl;
procedure SetSomeSpecialControl(const Value: TControl);
procedure SomeSpecialControlFreeNotification(const Sender:
TFreeNotificationObserver);
public
constructor Create(AOwner: TComponent); override;
property SomeSpecialControl: TControl
read FSomeSpecialControl write SetSomeSpecialControl;
end;
implementation
47
Modern Object Pascal Introduction for Programmers
uses CastleComponentSerialize;
constructor TContainer.Create(AOwner: TComponent);
begin
inherited;
FSomeSpecialControlObserver := TFreeNotificationObserver.Create(Self);
FSomeSpecialControlObserver.OnFreeNotification := {$ifdef FPC}@{$endif}
SomeSpecialControlFreeNotification;
end;
procedure TContainer.SetSomeSpecialControl(const Value: TControl);
begin
if FSomeSpecialControl <> Value then
begin
FSomeSpecialControl := Value;
FSomeSpecialControlObserver.Observed := Value;
end;
end;
procedure TContainer.SomeSpecialControlFreeNotification(const Sender:
TFreeNotificationObserver);
begin
// set property to nil when the referenced component is freed
SomeSpecialControl := nil;
end;
See https://castle-engine.io/custom_components .
6. Exceptions
6.1. Overview
Exceptions allow to interrupt the normal execution of the code.
• 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.
• 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.
Note: If an exception is raised but never caught, it will cause the entire application
to stop with an error.
48
Modern Object Pascal Introduction for Programmers
# But in LCL applications, the exceptions are always caught around events (and
cause LCL dialog box) if you don’t catch them earlier.
# In Castle Game Engine applications using CastleWindow , we similarly always
catch exceptions around your events (and display proper dialog box).
# So it is not so easy to make an exception that is not caught anywhere (not caught
in your code, LCL code, CGE code…).
• 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.
The 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.
An "exception" is, in general, any class instance.
• 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.
• 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.
• Exception classes (by convention) have names that start with E , not T . Like
ESomethingBadHappened .
• The compiler will automatically free exception object when it is handled. Don’t free
it yourself.
In 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.') .
6.2. Raising
If you want to raise your own exception, declare it and call raise … when appropriate:
type
49
Modern Object Pascal Introduction for Programmers
EInvalidParameter = class(Exception);
function ReadParameter: String;
begin
Result := Readln;
if Pos(' ', Result) <> 0 then
raise EInvalidParameter.Create('Invalid parameter, space is not
allowed');
end;
Note that the expression following the raise should be a valid class instance to raise.
You will almost always create the exception instance here.
You 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:
type
EInvalidParameter = class(Exception);
function ReadParameter: String;
begin
Result := Readln;
if Pos(' ', Result) <> 0 then
raise EInvalidParameter.CreateFmt('Invalid parameter %s, space is not
allowed', [Result]);
end;
6.3. Catching
You can catch an exception like this:
var
Parameter1, Parameter2, Parameter3: String;
begin
try
WriteLn('Input 1st parameter:');
Parameter1 := ReadParameter;
WriteLn('Input 2nd parameter:');
Parameter2 := ReadParameter;
WriteLn('Input 3rd parameter:');
50
Modern Object Pascal Introduction for Programmers
Parameter3 := ReadParameter;
except
// capture EInvalidParameter raised by one of the above ReadParameter
calls
on EInvalidParameter do
WriteLn('EInvalidParameter exception occurred');
end;
end;
To 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:
try
...
except
on E: EInvalidParameter do
WriteLn('EInvalidParameter exception occurred with message: ' +
E.Message);
end;
One could also test for multiple exception classes:
try
...
except
on E: EInvalidParameter do
WriteLn('EInvalidParameter exception occurred with message: ' +
E.Message);
on E: ESomeOtherException do
WriteLn('ESomeOtherException exception occurred with message: ' +
E.Message);
end;
You can also react to any exception raised, if you don’t use any on expression:
try
...
except
WriteLn('Warning: Some exception occurred');
end;
// WARNING: DO NOT FOLLOW THIS EXAMPLE WITHOUT READING A WARNING BELOW
// ABOUT "CAPTURING ALL EXCEPTIONS"
51
Modern Object Pascal Introduction for Programmers
In 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.
• Does the exception indicate a problem in user input? Then you should report it to
user.
• Does the exception indicate a bug in your code? Then you should fix the code, to
avoid the exception from happening at all.
Another way to capture all exceptions is to use:
try
...
except
on E: TObject do
WriteLn('Warning: Some exception occurred');
end;
// WARNING: DO NOT FOLLOW THIS EXAMPLE WITHOUT READING A WARNING ABOVE
// ABOUT "CAPTURING ALL EXCEPTIONS"
Although usually it is enough to capture Exception :
try
...
except
on E: Exception do
WriteLn('Warning: Some exception occurred: ' + E.ClassName + ',
message: ' + E.Message);
end;
// WARNING: DO NOT FOLLOW THIS EXAMPLE WITHOUT READING A WARNING ABOVE
// ABOUT "CAPTURING ALL EXCEPTIONS"
You 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:
try
52
Modern Object Pascal Introduction for Programmers
...
except
on E: EInvalidSoundFile do
begin
if E.InvalidUrl = 'http://example.com/blablah.wav' then
WriteLn('Warning: loading http://example.com/blablah.wav failed,
ignore it')
else
raise;
end;
end;
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’s handled.
6.4. Finally (doing things regardless if an exception occurred)
Often you use try .. finally .. end construction to free an instance of some
object, regardless if an exception occurred when using this object. The way to write
it looks like this:
procedure MyProcedure;
var
MyInstance: TMyClass;
begin
MyInstance := TMyClass.Create;
try
MyInstance.DoSomething;
MyInstance.DoSomethingElse;
finally
FreeAndNil(MyInstance);
end;
end;
This works reliably always, and does not cause memory
MyInstance.DoSomething or MyInstance.DoSomethingElse
exception.
leaks, even
if
raise an
Note 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:
53
Modern Object Pascal Introduction for Programmers
// INCORRECT EXAMPLE:
procedure MyProcedure;
var
MyInstance: TMyClass;
begin
try
CallSomeOtherProcedure;
MyInstance := TMyClass.Create;
MyInstance.DoSomething;
MyInstance.DoSomethingElse;
finally
FreeAndNil(MyInstance);
end;
end;
is not
if an exception occurs within
The above example
valid:
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.
Sometimes 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:
procedure MyProcedure;
var
MyInstance1: TMyClass1;
MyInstance2: TMyClass2;
MyInstance3: TMyClass3;
begin
MyInstance1 := TMyClass1.Create;
try
MyInstance1.DoSomething;
MyInstance2 := TMyClass2.Create;
try
MyInstance2.DoSomethingElse;
MyInstance3 := TMyClass3.Create;
54
Modern Object Pascal Introduction for Programmers
try
MyInstance3.DoYetAnotherThing;
finally
FreeAndNil(MyInstance3);
end;
finally
FreeAndNil(MyInstance2);
end;
finally
FreeAndNil(MyInstance1);
end;
end;
It is probably more readable in the form below:
procedure MyProcedure;
var
MyInstance1: TMyClass1;
MyInstance2: TMyClass2;
MyInstance3: TMyClass3;
begin
MyInstance1 := nil;
MyInstance2 := nil;
MyInstance3 := nil;
try
MyInstance1 := TMyClass1.Create;
MyInstance1.DoSomething;
MyInstance2 := TMyClass2.Create;
MyInstance2.DoSomethingElse;
MyInstance3 := TMyClass3.Create;
MyInstance3.DoYetAnotherThing;
finally
FreeAndNil(MyInstance3);
FreeAndNil(MyInstance2);
FreeAndNil(MyInstance1);
end;
end;
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.
55
Modern Object Pascal Introduction for Programmers
The final section in the try .. finally .. end block executes in most possible
scenarios when you leave the main code. Consider this:
try
A;
finally
B;
end;
So B will execute if
• The A raised (and didn’t catch) an exception.
• Or you will call Exit or (if you’re in the loop) Break or Continue right after
calling A .
• 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.
The only way to really avoid the B being executed is to unconditionally interrupt the
application process using Halt or some platform-specific APIs (like libc exit on Unix 2)
inside A . Which generally shall 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.
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.
An example of try .. finally .. end together with Exit calls:
procedure MyProcedure;
begin
try
WriteLn('Do something');
Exit;
WriteLn('This will not happen');
finally
WriteLn('This will happen regardless if we have left the block through
Exception, Exit, Continue, Break, etc.');
end;
2
https://www.man7.org/linux/man-pages/man3/exit.3.html
56
Modern Object Pascal Introduction for Programmers
WriteLn('This will not happen');
end;
See the Section 6, “Exceptions” chapter for more in-depth description of exceptions
including how to raise them and use try … except … end to catch them.
6.5. How the exceptions are displayed by various libraries
• In case of Lazarus LCL,
the exceptions raised during events (various
to OnXxx properties of LCL components) will be
captured and will result in a nice dialog message, that allows the user
callbacks assigned
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 .
• 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 .
• Some other GUI libraries may do a similar thing to above.
• In case of other applications, you can configure how the exception is displayed by
assigning a global callback to OnHaltProgram .
7. Run-time library
7.1. Input/output using streams
Modern programs should use TStream class and its many descendants to do input /
output. It has many useful descendants, like TFileStream , TMemoryStream ,
TStringStream .
{$mode objfpc}{$H+}{$J-}
uses
SysUtils, Classes;
var
S: TStream;
InputInt, OutputInt: Integer;
begin
InputInt := 666;
57
Modern Object Pascal Introduction for Programmers
S := TFileStream.Create('my_binary_file.data', fmCreate);
try
S.WriteBuffer(InputInt, SizeOf(InputInt));
finally
FreeAndNil(S);
end;
S := TFileStream.Create('my_binary_file.data', fmOpenRead);
try
S.ReadBuffer(OutputInt, SizeOf(OutputInt));
finally
FreeAndNil(S);
end;
WriteLn('Read from file got integer: ', OutputInt);
end.
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:
EnableNetwork := true;
S := Download('https://castle-engine.io/latest.zip');
S := Download('file:///home/michalis/my_binary_file.data');
S := Download('castle-data:/gui/my_image.png');
To read text files, we advise using the TTextReader class. It provides a line-oriented
API, and wraps a TStream inside. The TTextReader constructor can take a ready
URL, or you can pass there your custom TStream source.
Text := TTextReader.Create('castle-data:/my_data.txt');
try
while not Text.Eof do
WriteLnLog('NextLine', Text.ReadLn);
finally
FreeAndNil(Text);
58
Modern Object Pascal Introduction for Programmers
end;
7.2. Containers (lists, dictionaries) using generics
The 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.
The 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.
There are three libraries providing generics containers in FPC now:
• Generics.Collections unit and friends (since FPC >= 3.2.0)
• FGL unit
• GVector unit and friends (together in fcl-stl )
We advise using the Generics.Collections unit. The generic containers it
implements are
• packed with useful features,
• very efficient (in particular important for accessing dictionaries by keys),
• compatible between FPC and Delphi,
• the naming is consistent with other parts of the standard library (like the non-generic
containers from the Contnrs unit).
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!
Most important classes from the Generics.Collections unit are:
TList
A generic list of types.
TObjectList
A generic list of object instances. It can "own" children, which means that it will free
them automatically.
TDictionary
A generic dictionary.
59
Modern Object Pascal Introduction for Programmers
TObjectDictionary
A generic dictionary, that can "own" the keys and/or values.
Here’s how to you use a simple generic TObjectList :
{$mode objfpc}{$H+}{$J-}
uses SysUtils, Generics.Collections;
type
TApple = class
Name: string;
end;
TAppleList = specialize TObjectList<TApple>;
var
A: TApple;
Apples: TAppleList;
begin
Apples := TAppleList.Create(true);
try
A := TApple.Create;
A.Name := 'my apple';
Apples.Add(A);
A := TApple.Create;
A.Name := 'another apple';
Apples.Add(A);
Writeln('Count: ', Apples.Count);
Writeln(Apples[0].Name);
Writeln(Apples[1].Name);
finally FreeAndNil(Apples) end;
end.
Note that some operations require comparing two items, like sorting and searching (e.g.
by Sort and IndexOf methods). The Generics.Collections containers use
for this a comparer. 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 ).
When 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
60
Modern Object Pascal Introduction for Programmers
the appropriate callback, and use TComparer<T>.Construct method to wrap this
callback into an IComparer instance. An example of doing this is below:
{$mode objfpc}{$H+}{$J-}
uses SysUtils, Generics.Defaults, Generics.Collections;
type
TApple = class
Name: string;
end;
TAppleList = specialize TObjectList<TApple>;
function CompareApples(constref Left, Right: TApple): Integer;
begin
Result := AnsiCompareStr(Left.Name, Right.Name);
end;
type
TAppleComparer = specialize TComparer<TApple>;
var
A: TApple;
L: TAppleList;
begin
L := TAppleList.Create(true);
try
A := TApple.Create;
A.Name := '11';
L.Add(A);
A := TApple.Create;
A.Name := '33';
L.Add(A);
A := TApple.Create;
A.Name := '22';
L.Add(A);
L.Sort(TAppleComparer.Construct(@CompareApples));
Writeln('Count: ', L.Count);
Writeln(L[0].Name);
Writeln(L[1].Name);
Writeln(L[2].Name);
finally FreeAndNil(L) end;
61
Modern Object Pascal Introduction for Programmers
end.
The 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.
An example code using a dictionary:
{$mode objfpc}{$H+}{$J-}
uses SysUtils, Generics.Collections;
type
TApple = class
Name: string;
end;
TAppleDictionary = specialize TDictionary<string, TApple>;
var
Apples: TAppleDictionary;
A, FoundA: TApple;
ApplePair: TAppleDictionary.TDictionaryPair;
AppleKey: string;
begin
Apples := TAppleDictionary.Create;
try
A := TApple.Create;
A.Name := 'my apple';
Apples.AddOrSetValue('apple key 1', A);
if Apples.TryGetValue('apple key 1', FoundA) then
Writeln('Found apple under key "apple key 1" with name: ' +
FoundA.Name);
for AppleKey in Apples.Keys do
Writeln('Found apple key: ' + AppleKey);
for A in Apples.Values do
Writeln('Found apple value: ' + A.Name);
for ApplePair in Apples do
Writeln('Found apple key->value: ' +
ApplePair.Key + '->' + ApplePair.Value.Name);
{ Line below works too, but it can only be used to set
an *existing* dictionary key.
Instead of this, usually use AddOrSetValue
62
Modern Object Pascal Introduction for Programmers
to set or add a new key, as necessary. }
// Apples['apple key 1'] := ... ;
Apples.Remove('apple key 1');
{ Note that the TDictionary doesn't own the items,
you need to free them yourself.
We could use TObjectDictionary to have automatic ownership
mechanism. }
A.Free;
finally FreeAndNil(Apples) end;
end.
The 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.
An example code using
the TObjectDictionary
is below. Compile
this example with memory
leak detection,
-gh
generics_object_dictionary.lpr , to see that everything is freed when
program exits.
like fpc
-gl
{$mode objfpc}{$H+}{$J-}
uses SysUtils, Generics.Collections;
type
TApple = class
Name: string;
end;
TAppleDictionary = specialize TObjectDictionary<string, TApple>;
var
Apples: TAppleDictionary;
A: TApple;
ApplePair: TAppleDictionary.TDictionaryPair;
begin
Apples := TAppleDictionary.Create([doOwnsValues]);
try
A := TApple.Create;
A.Name := 'my apple';
Apples.AddOrSetValue('apple key 1', A);
63
Modern Object Pascal Introduction for Programmers
for ApplePair in Apples do
Writeln('Found apple key->value: ' +
ApplePair.Key + '->' + ApplePair.Value.Name);
Apples.Remove('apple key 1');
finally FreeAndNil(Apples) end;
end.
If you prefer using the FGL unit instead of Generics.Collections , the most
important classes from the FGL unit are:
TFPGList
A generic list of types.
TFPGObjectList
A generic list of object instances. It can "own" children.
TFPGMap
A generic dictionary.
In 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 Section 8.9, “Operator overloading”.
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.
If you want to know more about the generics, see Section 8.3, “Generics”.
7.3. Cloning: TPersistent.Assign
Copying the class instances by a simple assignment operator copies the reference.
var
X, Y: TMyObject;
begin
64
Modern Object Pascal Introduction for Programmers
X := TMyObject.Create;
Y := X;
// X and Y are now two pointers to the same data
Y.MyField := 123; // this also changes X.MyField
FreeAndNil(X);
end;
To 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:
var
X, Y: TMyObject;
begin
X := TMyObject.Create;
Y := TMyObject.Create;
Y.Assign(X);
Y.MyField := 123; // this does not change X.MyField
FreeAndNil(X);
FreeAndNil(Y);
end;
To 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.
{$mode objfpc}{$H+}{$J-}
uses
SysUtils, Classes;
type
TMyClass = class(TPersistent)
public
MyInt: Integer;
procedure Assign(Source: TPersistent); override;
end;
TMyClassDescendant = class(TMyClass)
public
MyString: string;
procedure Assign(Source: TPersistent); override;
end;
65
Modern Object Pascal Introduction for Programmers
procedure TMyClass.Assign(Source: TPersistent);
var
SourceMyClass: TMyClass;
begin
if Source is TMyClass then
begin
SourceMyClass := TMyClass(Source);
MyInt := SourceMyClass.MyInt;
// Xxx := SourceMyClass.Xxx; // add new fields here
end else
{ Since TMyClass is a direct TPersistent descendant,
it calls inherited ONLY when it cannot handle Source class.
See comments below. }
inherited Assign(Source);
end;
procedure TMyClassDescendant.Assign(Source: TPersistent);
var
SourceMyClassDescendant: TMyClassDescendant;
begin
if Source is TMyClassDescendant then
begin
SourceMyClassDescendant := TMyClassDescendant(Source);
MyString := SourceMyClassDescendant.MyString;
// Xxx := SourceMyClassDescendant.Xxx; // add new fields here
end;
{ Since TMyClassDescendant has an ancestor that already overrides
Assign (in TMyClass.Assign), it calls inherited ALWAYS,
to allow TMyClass.Assign to handle remaining fields.
See comments below for a detailed reasoning. }
inherited Assign(Source);
end;
var
C1, C2: TMyClass;
CD1, CD2: TMyClassDescendant;
begin
// test TMyClass.Assign
C1 := TMyClass.Create;
C2 := TMyClass.Create;
try
C1.MyInt := 666;
C2.Assign(C1);
WriteLn('C2 state: ', C2.MyInt);
66
Modern Object Pascal Introduction for Programmers
finally
FreeAndNil(C1);
FreeAndNil(C2);
end;
// test TMyClassDescendant.Assign
CD1 := TMyClassDescendant.Create;
CD2 := TMyClassDescendant.Create;
try
CD1.MyInt := 44;
CD1.MyString := 'blah';
CD2.Assign(CD1);
WriteLn('CD2 state: ', CD2.MyInt, ' ', CD2.MyString);
finally
FreeAndNil(CD1);
FreeAndNil(CD2);
end;
end.
Sometimes it’s more comfortable to alternatively override the AssignTo method in
the source class, instead of overriding the Assign method in the destination class.
Be careful when you call inherited in the overridden Assign implementation.
There are two situations:
Your 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.)
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.
Your class descends from some class that has already overridden the Assign
method.
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.
To 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:
procedure TPersistent.Assign(Source: TPersistent);
67
Modern Object Pascal Introduction for Programmers
begin
if Source <> nil then
Source.AssignTo(Self)
else
raise EConvertError...
end;
procedure TPersistent.AssignTo(Destination: TPersistent);
begin
raise EConvertError...
end;
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.
The conclusions you can get from the above are:
• If neither Assign nor AssignTo are overridden, then calling them will result in
an exception.
• 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.
When 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.
Assuming that you implemented TFruit.Assign and TApple.Assign following
the standard pattern (as shown in the example above), the effect is like this:
• If you pass TApple instance to TApple.Assign , it will work and copy all the
fields.
• 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 .
68
Modern Object Pascal Introduction for Programmers
• 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).
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 Section 4.5, “Visibility specifiers”.
8. Various language features
8.1. Local (nested) routines
Inside a larger routine (function, procedure, method) you can define a helper routine.
The 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.
These two examples are equivalent:
function SumOfSquares(const N: Integer): Integer;
function Square(const Value: Integer): Integer;
begin
Result := Value * Value;
end;
var
I: Integer;
begin
Result := 0;
for I := 0 to N do
Result := Result + Square(I);
end;
Another version, where we let the local routine Square to access I directly:
69
Modern Object Pascal Introduction for Programmers
function SumOfSquares(const N: Integer): Integer;
var
I: Integer;
function Square: Integer;
begin
Result := I * I;
end;
begin
Result := 0;
for I := 0 to N do
Result := Result + Square;
end;
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’t go too wild, or the
code will get unreadable:).
8.2. Callbacks (aka events, aka pointers to functions, aka
procedural variables)
They 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.
The callback can be:
• Normal, which means it can point to any normal routine (not a method, not local).
{$mode objfpc}{$H+}{$J-}
function Add(const A, B: Integer): Integer;
begin
Result := A + B;
end;
function Multiply(const A, B: Integer): Integer;
begin
Result := A * B;
end;
70
Modern Object Pascal Introduction for Programmers
type
TMyFunction = function (const A, B: Integer): Integer;
function ProcessTheList(const F: TMyFunction): Integer;
var
I: Integer;
begin
Result := 1;
for I := 2 to 10 do
Result := F(Result, I);
end;
var
SomeFunction: TMyFunction;
begin
SomeFunction := @Add;
WriteLn('1 + 2 + 3 ... + 10 = ', ProcessTheList(SomeFunction));
SomeFunction := @Multiply;
WriteLn('1 * 2 * 3 ... * 10 = ', ProcessTheList(SomeFunction));
end.
• A method: declare with of object at the end.
{$mode objfpc}{$H+}{$J-}
uses
SysUtils;
type
TMyMethod = procedure (const A: Integer) of object;
TMyClass = class
CurrentValue: Integer;
procedure Add(const A: Integer);
procedure Multiply(const A: Integer);
procedure ProcessTheList(const M: TMyMethod);
end;
procedure TMyClass.Add(const A: Integer);
begin
CurrentValue := CurrentValue + A;
end;
procedure TMyClass.Multiply(const A: Integer);
begin
71
Modern Object Pascal Introduction for Programmers
CurrentValue := CurrentValue * A;
end;
procedure TMyClass.ProcessTheList(const M: TMyMethod);
var
I: Integer;
begin
CurrentValue := 1;
for I := 2 to 10 do
M(I);
end;
var
C: TMyClass;
begin
C := TMyClass.Create;
try
C.ProcessTheList(@C.Add);
WriteLn('1 + 2 + 3 ... + 10 = ', C.CurrentValue);
C.ProcessTheList(@C.Multiply);
WriteLn('1 * 2 * 3 ... * 10 = ', C.CurrentValue);
finally
FreeAndNil(C);
end;
end.
Note 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 Section 9.3, “Class methods” as
methods.
type
TMyMethod = function (const A, B: Integer): Integer of object;
TMyClass = class
class function Add(const A, B: Integer): Integer
class function Multiply(const A, B: Integer): Integer
end;
var
M: TMyMethod;
begin
M := @TMyClass(nil).Add;
72
Modern Object Pascal Introduction for Programmers
M := @TMyClass(nil).Multiply;
end;
Unfortunately, you need to write ugly @TMyClass(nil).Add instead of just
@TMyClass.Add .
• 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 Section 8.1, “Local (nested) routines”.
8.3. Generics
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 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.
The generics in Pascal work much like generics in C++. Which means that they
are "expanded" at the 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.
{$mode objfpc}{$H+}{$J-}
uses
SysUtils;
type
generic TMyCalculator<T> = class
Value: T;
procedure Add(const A: T);
end;
procedure TMyCalculator.Add(const A: T);
begin
Value := Value + A;
end;
type
TMyFloatCalculator = specialize TMyCalculator<Single>;
73
Modern Object Pascal Introduction for Programmers
TMyStringCalculator = specialize TMyCalculator<string>;
var
FloatCalc: TMyFloatCalculator;
StringCalc: TMyStringCalculator;
begin
FloatCalc := TMyFloatCalculator.Create;
try
FloatCalc.Add(3.14);
FloatCalc.Add(1);
WriteLn('FloatCalc: ', FloatCalc.Value:1:2);
finally
FreeAndNil(FloatCalc);
end;
StringCalc := TMyStringCalculator.Create;
try
StringCalc.Add('something');
StringCalc.Add(' more');
WriteLn('StringCalc: ', StringCalc.Value);
finally
FreeAndNil(StringCalc);
end;
end.
Generics are not limited to classes, you can have generic functions and procedures
as well:
{$mode objfpc}{$H+}{$J-}
uses
SysUtils;
{ Note: this example requires FPC 3.1.1 (will not compile with FPC 3.0.0
or older). }
generic function Min<T>(const A, B: T): T;
begin
if A < B then
Result := A else
Result := B;
end;
begin
WriteLn('Min (1, 0): ', specialize Min<Integer>(1, 0));
WriteLn('Min (3.14, 5): ', specialize Min<Single>(3.14, 5):1:2);
74
Modern Object Pascal Introduction for Programmers
WriteLn('Min (''a'', ''b''): ', specialize Min<string>('a', 'b'));
end.
See also the Section 7.2, “Containers (lists, dictionaries) using generics” about
important standard classes using generics.
8.4. Overloading
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.
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
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.
8.5. Preprocessor
You can use simple preprocessor directives for
• conditional compilation (code depending on platform, or some custom switches),
• to include one file in another,
• you can also use parameter-less macros.
Note 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.
{$mode objfpc}{$H+}{$J-}
unit PreprocessorStuff;
interface
{$ifdef FPC}
{ This is only defined when compiled by FPC, not other compilers (like
Delphi). }
procedure Foo;
{$endif}
75
Modern Object Pascal Introduction for Programmers
{ Define a NewLine constant. Here you can see how the normal syntax of
Pascal
is "broken" by preprocessor directives. When you compile on Unix
(includes Linux, Android, macOS), the compiler sees this:
const NewLine = #10;
When you compile on Windows, the compiler sees this:
const NewLine = #13#10;
On other operating systems, the code will fail to compile,
because a compiler sees this:
const NewLine = ;
It's a *good* thing that the compilation fails in this case -- if you
will have to port the program to an OS that is not Unix, not Windows,
you will be reminded by a compiler to choose the newline convention
on that system. }
const
NewLine =
{$ifdef UNIX} #10 {$endif}
{$ifdef MSWINDOWS} #13#10 {$endif} ;
{$define MY_SYMBOL}
{$ifdef MY_SYMBOL}
procedure Bar;
{$endif}
{$define CallingConventionMacro := unknown}
{$ifdef UNIX}
{$define CallingConventionMacro := cdecl}
{$endif}
{$ifdef MSWINDOWS}
{$define CallingConventionMacro := stdcall}
{$endif}
procedure RealProcedureName;
CallingConventionMacro; external 'some_external_library';
implementation
76
Modern Object Pascal Introduction for Programmers
{$include some_file.inc}
// $I is just a shortcut for $include
{$I some_other_file.inc}
end.
Include files have commonly the .inc extension, and are used for two purposes:
• 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:
{$mode objfpc}
{$H+}
{$J-}
{$modeswitch advancedrecords}
{$ifndef VER3}
{$error This code can only be compiled using FPC version at least
3.x.}
{$endif}
Now you can include this file using {$I myconfig.inc} in all your sources.
• 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. Never the less, this is a useful technique.
1. 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.
2. It allows to have a cross-platform unit interface with platform-dependent
implementation easily. Basically you can do
{$ifdef UNIX} {$I my_unix_implementation.inc} {$endif}
{$ifdef MSWINDOWS} {$I my_windows_implementation.inc} {$endif}
77
Modern Object Pascal Introduction for Programmers
Sometimes 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.
8.6. Records
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.
If 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.
{$mode objfpc}{$H+}{$J-}
{$modeswitch advancedrecords}
type
TMyRecord = record
public
I, Square: Integer;
procedure WriteLnDescription;
end;
procedure TMyRecord.WriteLnDescription;
begin
WriteLn('Square of ', I, ' is ', Square);
end;
var
A: array [0..9] of TMyRecord;
R: TMyRecord;
I: Integer;
begin
for I := 0 to 9 do
begin
A[I].I := I;
A[I].Square := I * I;
78
Modern Object Pascal Introduction for Programmers
end;
for R in A do
R.WriteLnDescription;
end.
In 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.
But records are still very useful when you need speed or a predictable memory layout:
• 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.
• Arrays of records are nicely linear in memory, so they are cache-friendly.
• 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:
# to communicate with libraries written in other programming languages, when they
expose an API based on records,
# to read and write binary files,
# to make dirty low-level tricks (like unsafe typecasting one type to another, being
aware of their memory representation).
• 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:)
8.7. Old-style objects
In 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 .
• The old-style objects can be allocated / freed, and during that operation you can
call their constructor / destructor.
79
Modern Object Pascal Introduction for Programmers
• 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.
• 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.
It’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.
8.8. Pointers
You 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:
type
PMyRecord = ^TMyRecord;
TMyRecord = record
Value: Integer;
Next: PMyRecord;
end;
Note 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.
You 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 ).
There 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.
80
Modern Object Pascal Introduction for Programmers
Remember that a class instance is also in fact a pointer, although it doesn’t require any
^ or @ operators to use it. A linked list using classes is certainly possible, it would
simply be this:
type
TMyClass = class
Value: Integer;
Next: TMyClass;
end;
8.9. Operator overloading
You can override the meaning of many language operators, for example to allow
addition and multiplication of your custom types. Like this:
{$mode objfpc}{$H+}{$J-}
uses
StrUtils;
operator* (const S: string; const A: Integer): string;
begin
Result := DupeString(S, A);
end;
begin
WriteLn('bla' * 10);
end.
You can override 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.
{$mode objfpc}{$H+}{$J-}
uses
SysUtils;
type
TMyClass = class
MyInt: Integer;
end;
operator* (const C1, C2: TMyClass): TMyClass;
begin
81
Modern Object Pascal Introduction for Programmers
Result := TMyClass.Create;
Result.MyInt := C1.MyInt * C2.MyInt;
end;
var
C1, C2: TMyClass;
begin
C1 := TMyClass.Create;
try
C1.MyInt := 12;
C2 := C1 * C1;
try
WriteLn('12 * 12 = ', C2.MyInt);
finally
FreeAndNil(C2);
end;
finally
FreeAndNil(C1);
end;
end.
You can override operators on records too. This is usually easier than overloading them
for classes, as the caller doesn’t have to deal then with memory management.
{$mode objfpc}{$H+}{$J-}
uses
SysUtils;
type
TMyRecord = record
MyInt: Integer;
end;
operator* (const C1, C2: TMyRecord): TMyRecord;
begin
Result.MyInt := C1.MyInt * C2.MyInt;
end;
var
R1, R2: TMyRecord;
begin
R1.MyInt := 12;
R2 := R1 * R1;
WriteLn('12 * 12 = ', R2.MyInt);
82
Modern Object Pascal Introduction for Programmers
end.
For records, it’s advised to use {$modeswitch advancedrecords} and override
operators as class operator inside the record. This allows to use generic classes
that depend on some operator existence (like TFPGList , that depends on 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> .
{$mode objfpc}{$H+}{$J-}
{$modeswitch advancedrecords}
uses
SysUtils, FGL;
type
TMyRecord = record
MyInt: Integer;
class operator+ (const C1, C2: TMyRecord): TMyRecord;
class operator= (const C1, C2: TMyRecord): boolean;
end;
class operator TMyRecord.+ (const C1, C2: TMyRecord): TMyRecord;
begin
Result.MyInt := C1.MyInt + C2.MyInt;
end;
class operator TMyRecord.= (const C1, C2: TMyRecord): boolean;
begin
Result := C1.MyInt = C2.MyInt;
end;
type
TMyRecordList = specialize TFPGList<TMyRecord>;
var
R, ListItem: TMyRecord;
L: TMyRecordList;
begin
L := TMyRecordList.Create;
try
R.MyInt := 1; L.Add(R);
R.MyInt := 10; L.Add(R);
R.MyInt := 100; L.Add(R);
83
Modern Object Pascal Introduction for Programmers
R.MyInt := 0;
for ListItem in L do
R := ListItem + R;
WriteLn('1 + 10 + 100 = ', R.MyInt);
finally
FreeAndNil(L);
end;
end.
9. Advanced classes features
9.1. Private and strict private
The private visibility specifier means that the field (or method) is not accessible
outside of this class. But it allows an exception: all the code defined in the same unit can
break this, and access private fields and methods. A C++ programmer would say that
in Pascal all classes within a single unit are friends. This is often useful, and doesn’t
break your encapsulation, since it’s limited to a unit.
However, if you create larger units, with many classes (that are not tightly integrated
with each other), it’s safer to use strict private . It means that the field (or method)
is not accessible outside of this class — period. No exceptions.
In a similar manner, there’s protected visibility (visible to descendants, or friends in
the same unit) and strict protected (visible to descendants, period).
9.2. More stuff inside classes and nested classes
You can open a section of constants ( const ) or types ( type ) within a class. This
way, you can even define a class within a class. The visibility specifiers work as always,
in particular the nested class can be private (not visible to the outside world), which
is often useful.
Note that to declare a field after a constant or type you will need to open a var block.
type
TMyClass = class
private
type
TInternalClass = class
84
Modern Object Pascal Introduction for Programmers
Velocity: Single;
procedure DoSomething;
end;
var
FInternalClass: TInternalClass;
public
const
DefaultVelocity = 100.0;
constructor Create;
destructor Destroy; override;
end;
constructor TMyClass.Create;
begin
inherited;
FInternalClass := TInternalClass.Create;
FInternalClass.Velocity := DefaultVelocity;
FInternalClass.DoSomething;
end;
destructor TMyClass.Destroy;
begin
FreeAndNil(FInternalClass);
inherited;
end;
{ note that method definition is prefixed with
"TMyClass.TInternalClass" below. }
procedure TMyClass.TInternalClass.DoSomething;
begin
end;
9.3. Class methods
These are methods you can call having a class reference ( TMyClass ), not necessarily
a class instance.
type
TEnemy = class
procedure Kill;
class procedure KillAll;
end;
var
85
Modern Object Pascal Introduction for Programmers
E: TEnemy;
begin
E := TEnemy.Create;
try
E.Kill;
finally FreeAndNil(E) end;
TEnemy.KillAll;
end;
Note that they can be virtual — it makes sense, and is sometimes very useful, when
combined with Section 9.4, “Class references”.
The class methods can also be limited by the Section 4.5, “Visibility specifiers”, like
private or protected . Just like regular methods.
Note that a constructor always acts like a class method when called in a normal fashion
( MyInstance := TMyClass.Create(…); ). Although it’s possible to also call a
constructor from within the class itself, like a normal method, and then it acts like a
normal method. This is a useful feature to "chain" constructors, when one constructor
(e.g. overloaded to take an integer parameter) does some job, and then calls another
constructor (e.g. parameter-less).
9.4. Class references
Class reference allows you to choose the class at runtime, for example to call a class
method or constructor without knowing the exact class at compile-time. It is a type
declared as class of TMyClass .
type
TMyClass = class(TComponent)
end;
TMyClass1 = class(TMyClass)
end;
TMyClass2 = class(TMyClass)
end;
TMyClassRef = class of TMyClass;
var
C: TMyClass;
ClassRef: TMyClassRef;
86
Modern Object Pascal Introduction for Programmers
begin
// Obviously you can do this:
C := TMyClass.Create(nil); FreeAndNil(C);
C := TMyClass1.Create(nil); FreeAndNil(C);
C := TMyClass2.Create(nil); FreeAndNil(C);
// In addition, using class references, you can also do this:
ClassRef := TMyClass;
C := ClassRef.Create(nil); FreeAndNil(C);
ClassRef := TMyClass1;
C := ClassRef.Create(nil); FreeAndNil(C);
ClassRef := TMyClass2;
C := ClassRef.Create(nil); FreeAndNil(C);
end;
Class references can be combined with virtual class methods. This gives a similar
effect as using classes with virtual methods — the actual method to be executed is
determined at runtime.
type
TMyClass = class(TComponent)
class procedure DoSomething; virtual; abstract;
end;
TMyClass1 = class(TMyClass)
class procedure DoSomething; override;
end;
TMyClass2 = class(TMyClass)
class procedure DoSomething; override;
end;
TMyClassRef = class of TMyClass;
var
C: TMyClass;
ClassRef: TMyClassRef;
begin
ClassRef := TMyClass1;
ClassRef.DoSomething;
87
Modern Object Pascal Introduction for Programmers
ClassRef := TMyClass2;
ClassRef.DoSomething;
{ And this will cause an exception at runtime,
since DoSomething is abstract in TMyClass. }
ClassRef := TMyClass;
ClassRef.DoSomething;
end;
If you have an instance, and you would like to get a reference to its class (not the
declared class, but the final descendant class used at its construction), you can use the
ClassType property. The declared type of ClassType is TClass , which stands
for class of TObject . Often you can safely typecast it to something more specific,
when you know that the instance is something more specific than TObject .
In particular, you can use the ClassType reference to call virtual methods, including
virtual constructors. This allows you to create a method like Clone that constructs
an instance of the exact run-time class of the current object. You can combine it with
Section 7.3, “Cloning: TPersistent.Assign” to have a method that returns a newly-
constructed clone of the current instance.
Remember that it only works when the constructor of your class is virtual. For example,
it can be used with the standard TComponent descendants, since they all must
override TComponent.Create(AOwner: TComponent) virtual constructor.
type
TMyClass = class(TComponent)
procedure Assign(Source: TPersistent); override;
function Clone(AOwner: TComponent): TMyClass;
end;
TMyClassRef = class of TMyClass;
function TMyClass.Clone(AOwner: TComponent): TMyClass;
begin
// This would always create an instance of exactly TMyClass:
//Result := TMyClass.Create(AOwner);
// This can potentially create an instance of TMyClass descendant:
Result := TMyClassRef(ClassType).Create(AOwner);
Result.Assign(Self);
end;
88
Modern Object Pascal Introduction for Programmers
9.5. Static class methods
To understand the static class methods, you have to understand how the normal class
methods (described in the previous sections) work. Internally, normal class methods
receive a class reference of their class (it is passed through a hidden, implicitly added
1st parameter of the method). This class reference can be even accessed explicitly
using the Self keyword inside the class method. Usually, it’s a good thing: this class
reference allows you to call virtual class methods (through the virtual method table of
the class).
While this is nice, it makes the normal class methods incompatible when assigning to
a global procedure pointer. That is, this will not compile:
{$mode objfpc}{$H+}{$J-}
type
TMyCallback = procedure (A: Integer);
TMyClass = class
class procedure Foo(A: Integer);
end;
class procedure TMyClass.Foo(A: Integer);
begin
end;
var
Callback: TMyCallback;
begin
// Error: TMyClass.Foo not compatible with TMyCallback
Callback := @TMyClass(nil).Foo;
end.
In the Delphi mode you would be able to write TMyClass.Foo
instead of an ugly TMyClass(nil).Foo in the example above.
looks much more elegant,
Admittedly,
the TMyClass.Foo
and it is also better checked by the compiler. Using the
TMyClass(nil).Foo is a hack… unfortunately, necessary (for
now) in the ObjFpc mode which is presented throughout this book.
In any case, assigning the TMyClass.Foo to the Callback
above would still fail in the Delphi mode, for exactly the same
reasons.
89
Modern Object Pascal Introduction for Programmers
The above example fails to compile, because the Callback is incompatible with the
class method Foo . And it’s incompatible because internally the class method has that
special hidden implicit parameter to pass a class reference.
One way to fix the above example is to change the definition of TMyCallback . It
will work if it is a method callback, declared as TMyCallback = procedure (A:
Integer) of object; . But sometimes, it’s not desirable.
Here comes the static class method. It is, in essence, just a global procedure /
function, but its namespace is limited inside the class. It does not have any implicit
class reference (and so, it cannot be virtual and it cannot call virtual class methods).
On the upside, it is compatible with normal (non-object) callbacks. So this will work:
{$mode objfpc}{$H+}{$J-}
type
TMyCallback = procedure (A: Integer);
TMyClass = class
class procedure Foo(A: Integer); static;
end;
class procedure TMyClass.Foo(A: Integer);
begin
end;
var
Callback: TMyCallback;
begin
Callback := @TMyClass.Foo;
end.
9.6. Class properties and variables
A class property is a property that can be accessed through a class reference (it does
not need a class instance).
It is quite straightforward analogy of a regular property (see Section 4.3, “Properties”).
For a class property, you define a getter and / or a setter. They may refer to a class
variable or a static class method.
A class variable is, you guessed it, like a regular field but you don’t need a class instance
to access it. In effect, it’s just like a global variable, but with the namespace limited to
the containing class. It can be declared within the class var section of the class.
90
Modern Object Pascal Introduction for Programmers
Alternatively it can be declared by following the normal field definition with the keyword
static .
And a static class method is just like a global procedure / function, but with the
namespace limited to the containing class. More about static class methods in the
section above, see Section 9.5, “Static class methods”.
{$mode objfpc}{$H+}{$J-}
type
TMyClass = class
strict private
// Alternative:
// FMyProperty: Integer; static;
class var
FMyProperty: Integer;
class procedure SetMyProperty(const Value: Integer); static;
public
class property MyProperty: Integer
read FMyProperty write SetMyProperty;
end;
class procedure TMyClass.SetMyProperty(const Value: Integer);
begin
Writeln('MyProperty changes!');
FMyProperty := Value;
end;
begin
TMyClass.MyProperty := 123;
Writeln('TMyClass.MyProperty is now ', TMyClass.MyProperty);
end.
9.7. Class helpers
The method is just a procedure or function inside a class. From the outside of the
class, you call it with a special syntax MyInstance.MyMethod(…) . After a while you
grow accustomed to thinking that if I want to make action Action on instance X, I write
`X.Action(…)`.
But sometimes, you need to implement something that conceptually is an action
on class TMyClass without modifying the TMyClass source code. Sometimes it’s
because it’s not your source code, and you don’t want to change it. Sometimes
it’s because of the dependencies — adding a method like Render to a class like
91
Modern Object Pascal Introduction for Programmers
TMy3DObject seems like a straightforward idea, but maybe the base implementation
of class TMy3DObject should be kept independent from the rendering code? It would
be better to "enhance" an existing class, to add functionality to it without changing its
source code.
Simple way to do it is then to create a global procedure that takes an instance of
TMy3DObject as its 1st parameter.
procedure Render(const Obj1: TMy3DObject; const Color: TColor);
var
I: Integer;
begin
for I := 0 to Obj1.ShapesCount - 1 do
RenderMesh(Obj1.Shape[I].Mesh, Color);
end;
This works perfectly, but the downside is that calling it looks a little ugly. While usually
you call actions like X.Action(…) , in this case you have to call them like Render(X,
…) . It would be cool to be able to just write X.Render(…) , even when Render is
not implemented in the same unit as TMy3DObject .
And this is where you use class helpers. They are just a way to implement procedures /
functions that operate on given class, and that are called like methods, but are not in
fact normal methods — they were added outside of the TMy3DObject definition.
type
TMy3DObjectHelper = class helper for TMy3DObject
procedure Render(const Color: TColor);
end;
procedure TMy3DObjectHelper.Render(const Color: TColor);
var
I: Integer;
begin
{ note that we access ShapesCount, Shape without any qualifiers here }
for I := 0 to ShapesCount - 1 do
RenderMesh(Shape[I].Mesh, Color);
end;
The more general concept is "type helper". Using them you can add
methods even to primitive types, like integers or enums. You can
92
Modern Object Pascal Introduction for Programmers
also add "record helpers" to (you guessed it…) records. See http://
lists.freepascal.org/fpc-announce/2013-February/000587.html .
9.8. Virtual constructors, destructors
Destructor name is always Destroy , it is virtual (since you can call it without knowing
the exact class at compile-time) and parameter-less.
Constructor name is by convention Create .
You can change this name, although be careful with this — if you define CreateMy ,
always redefine also the name Create , otherwise the user can still access the
constructor Create of the ancestor, bypassing your CreateMy constructor.
In the base TObject it is not virtual, and when creating descendants you’re free to
change the parameters. The new constructor will hide the constructor in ancestor (note:
don’t put here overload , unless you want to break it).
the TComponent descendants, you should override
its constructor
In
Create(AOwner: TComponent); . For streaming functionality, to create a class
without knowing its type at compile time, having virtual constructors is very useful (see
Section 9.4, “Class references” above).
9.9. An exception in constructor
What happens if an exception happens during a constructor? The line
X := TMyClass.Create;
does not execute to the end in this case, X cannot be assigned, so who will cleanup
after a partially-constructed class?
The solution of Object Pascal is that, in case an exception occurs within a constructor,
then the destructor is called. This is a reason why your destructor must be robust, which
means it should work in any circumstances, even on a half-created class instance.
Usually this is easy if you release everything safely, like by FreeAndNil .
We also have to depend in such cases that the memory of the class is guaranteed to be
zeroed right before the constructor code is executed. So we know that at the beginning,
all class references are nil , all integers are 0 and so on.
93
Modern Object Pascal Introduction for Programmers
So below works without any memory leaks:
{$mode objfpc}{$H+}{$J-}
uses
SysUtils;
type
TGun = class
end;
TPlayer = class
Gun1, Gun2: TGun;
constructor Create;
destructor Destroy; override;
end;
constructor TPlayer.Create;
begin
inherited;
Gun1 := TGun.Create;
raise Exception.Create('Raising an exception from constructor!');
Gun2 := TGun.Create;
end;
destructor TPlayer.Destroy;
begin
{ in case since the constructor crashed, we can
have Gun1 <> nil and Gun2 = nil now. Deal with it.
...Actually, in this case, FreeAndNil deals with it without
any additional effort on our side, because FreeAndNil checks
whether the instance is nil before calling its destructor. }
FreeAndNil(Gun1);
FreeAndNil(Gun2);
inherited;
end;
begin
try
TPlayer.Create;
except
on E: Exception do
WriteLn('Caught ' + E.ClassName + ': ' + E.Message);
end;
end.
94
Modern Object Pascal Introduction for Programmers
10. Interfaces
10.1. Bare (CORBA) interfaces
An interface declares an API, much like a class, but it does not define the
implementation. A class can implement many interfaces, but it can only have one
ancestor class.
You can cast a class to any interface it supports, and then call the methods through
that interface. This allows to treat in a uniform fashion the classes that don’t descend
from each other, but still share some common functionality. Useful when a simple class
inheritance is not enough.
The CORBA interfaces in Object Pascal work pretty much like interfaces in Java
(https://docs.oracle.com/javase/tutorial/java/concepts/interface.html) or C# (https://
msdn.microsoft.com/en-us/library/ms173156.aspx).
{$mode objfpc}{$H+}{$J-}
{$interfaces corba}
uses
SysUtils, Classes;
type
IMyInterface = interface
['{79352612-668B-4E8C-910A-26975E103CAC}']
procedure Shoot;
end;
TMyClass1 = class(IMyInterface)
procedure Shoot;
end;
TMyClass2 = class(IMyInterface)
procedure Shoot;
end;
TMyClass3 = class
procedure Shoot;
end;
procedure TMyClass1.Shoot;
begin
95
Modern Object Pascal Introduction for Programmers
WriteLn('TMyClass1.Shoot');
end;
procedure TMyClass2.Shoot;
begin
WriteLn('TMyClass2.Shoot');
end;
procedure TMyClass3.Shoot;
begin
WriteLn('TMyClass3.Shoot');
end;
procedure UseThroughInterface(I: IMyInterface);
begin
Write('Shooting... ');
I.Shoot;
end;
var
C1: TMyClass1;
C2: TMyClass2;
C3: TMyClass3;
begin
C1 := TMyClass1.Create;
C2 := TMyClass2.Create;
C3 := TMyClass3.Create;
try
if C1 is IMyInterface then
UseThroughInterface(C1 as IMyInterface);
if C2 is IMyInterface then
UseThroughInterface(C2 as IMyInterface);
// The "C3 is IMyInterface" below is false,
// so "UseThroughInterface(C3 as IMyInterface)" will not execute.
if C3 is IMyInterface then
UseThroughInterface(C3 as IMyInterface);
finally
FreeAndNil(C1);
FreeAndNil(C2);
FreeAndNil(C3);
end;
end.
96
Modern Object Pascal Introduction for Programmers
10.2. CORBA and COM types of interfaces
Why are the interfaces (presented above) called "CORBA"?
The name CORBA is unfortunate. A better name would be bare interfaces. These
interfaces are a "pure language feature". Use them when you want to cast various
classes as the same interface, because they share a common API.
While these types of interfaces can be used together with the CORBA (Common
Object Request Broker Architecture) technology (see wikipedia about CORBA 3),
they are not tied to this technology in any way.
Is the {$interfaces corba} declaration needed?
Yes, because by default you create COM interfaces. This can be stated explicitly
by saying {$interfaces com} , but usually it’s not needed since it’s the default
state.
And I don’t advise using COM interfaces, especially if you’re looking for something
equivalent to interfaces from other programming languages. The CORBA interfaces
in Pascal are exactly what you expect if you’re looking for something equivalent to
the interfaces in C# and Java. While the COM interfaces bring additional features
that you possibly don’t want.
Note that the {$interfaces xxx} declaration only affects the interfaces
that do not have any explicit ancestor (just the keyword interface , not
interface(ISomeAncestor) ). When an interface has an ancestor, it has the
same type as the ancestor, regardless of the {$interfaces xxx} declaration.
What are COM interfaces?
The COM interface is synonymous with an interface descending from a special
IUnknown interface. Descending from IUnknown :
• Requires that your classes define the _AddRef and _ReleaseRef methods.
Proper implementation of these methods can manage the lifetime of your objects
using the reference-counting.
• Adds the QueryInterface method.
• Allows to interact with the COM (Component Object Model) technology.
3
https://en.wikipedia.org/wiki/Common_Object_Request_Broker_Architecture
97
Modern Object Pascal Introduction for Programmers
Why do you advise to not use the COM interfaces?
Because COM interfaces "entangle" two features that should be unrelated
(orthogonal) in my view: multiple inheritance and reference counting. Other
programming languages rightly use separate concepts for these two features.
To be clear: reference-counting, that provides an automatic memory management
(in simple situations, i.e. without cycles), is a very useful concept. But entangling
this feature with interfaces (instead of making them orthogonal features) is
unclean in my eyes. It definitely doesn’t match my use cases.
• Sometimes I want to cast my (otherwise unrelated) classes to a common
interface.
• Sometimes I want to manage memory using the reference counting approach.
• Maybe some day I will want to interact with the COM technology.
But these are all separate, unrelated needs. Entangling them in a single language
feature is counter-useful in my experience. It does cause actual problems:
• If I want the feature of casting classes to a common interface API, but I don’t
want the reference-counting mechanism (I want to manually free objects), then
the COM interfaces are problematic. Even when reference-counting is disabled
by a special _AddRef and _ReleaseRef implementation, you still need to be
careful to never have a temporary interface reference hanging, after you have
freed the class instance. More details about it in the next section.
• If I want the feature of reference counting, but I have no need for an interface
hierarchy to represent something different than the class hierarchy, then I have
to duplicate my classes API in interfaces. Thus creating a single interface for
each class. This is counter-productive. I would much rather have smart pointers
as a separate language feature, not entangled with interfaces (and luckily, it’s
coming:).
That is why I advise to use CORBA style interfaces, and the {$interfaces
corba} directive, in all modern code dealing with interfaces.
Only if you need both "reference counting" and "multiple inheritance" at the same
time, then use COM interfaces. Also, Delphi has only COM interfaces for now, so
you need to use COM interfaces if your code must be compatible with Delphi.
Can we have reference-counting with CORBA interfaces?
Yeah. Just add _AddRef / _ReleaseRef methods. There’s no need to descend
from the IUnknown interface. Although in most cases, if you want reference-
counting with your interfaces, you may as well just use COM interfaces.
98
Modern Object Pascal Introduction for Programmers
10.3. Interfaces GUIDs
GUIDs are the seemingly random characters ['{ABCD1234-…}'] that you see
placed at every interface definition. Yes, they are just random. Unfortunately, they are
necessary.
The GUIDs have no meaning if you don’t plan on integrating with communication
technologies like COM nor CORBA. But they are necessary, for implementation
reasons. Don’t be fooled by the compiler, that unfortunately allows you to declare
interfaces without GUIDs.
Without the (unique) GUIDs, your interfaces will be treated equal by the is operator.
In effect, it will return true if your class supports any of your interfaces. The magic
function Supports(ObjectInstance, IMyInterface) behaves slightly better
here, as it refuses to be compiled for interfaces without a GUID. This is true for both
CORBA and COM interfaces, as of FPC 3.0.0.
So, to be on the safe side, you should always declare a GUID for your interface. You
can use Lazarus GUID generator ( Ctrl + Shift + G shortcut in the editor). Or
you can use an online service like https://www.guidgenerator.com/ .
Or you can write your own tool for this, using the CreateGUID and GUIDToString
functions in RTL. See the example below:
{$mode objfpc}{$H+}{$J-}
uses
SysUtils;
var
MyGuid: TGUID;
begin
Randomize;
CreateGUID(MyGuid);
WriteLn('[''' + GUIDToString(MyGuid) + ''']');
end.
10.4. Reference-counted (COM) interfaces
The COM interfaces bring two additional features:
1. integration with COM (a technology from Windows, also available on Unix through
XPCOM, used by Mozilla),
99
Modern Object Pascal Introduction for Programmers
2. reference counting (which gives you automatic destruction when all the interface
references go out of scope).
When using COM interfaces, you need to be aware of their automatic destruction
mechanism and relation to COM technology.
In practice, this means that:
• Your class needs
implement a magic _AddRef , _Release , and
QueryInterface methods. Or descend from something that already implements
them. A particular implementation of these methods may actually enable or disable
to
the reference-counting feature of COM interfaces (although disabling it is somewhat
dangerous — see the next point).
# The standard class TInterfacedObject implements these methods to
enable the reference-counting.
# The standard class TComponent implements these methods to disable the
reference-counting.
• You need to be careful of freeing the class, when it may be referenced by
some interface variables. Because the interface is released using a virtual method
(because it may be reference-counted, even if you hack the _AddRef method to not
be reference-counted…), you cannot free the underlying object instance as long as
some interface variable may point to it. See "7.7 Reference counting" in the FPC
manual (http://freepascal.org/docs-html/ref/refse47.html).
The safest approach to using COM interfaces is to
• accept the fact that they are reference-counted,
• derive the appropriate classes from TInterfacedObject ,
• and avoid using the class instance, instead accessing the instance always through
the interface, letting reference-counting manage the deallocation.
This is an example of such interface use:
{$mode objfpc}{$H+}{$J-}
{$interfaces com}
uses
SysUtils, Classes;
type
100
Modern Object Pascal Introduction for Programmers
IMyInterface = interface
['{3075FFCD-8EFB-4E98-B157-261448B8D92E}']
procedure Shoot;
end;
TMyClass1 = class(TInterfacedObject, IMyInterface)
procedure Shoot;
end;
TMyClass2 = class(TInterfacedObject, IMyInterface)
procedure Shoot;
end;
TMyClass3 = class(TInterfacedObject)
procedure Shoot;
end;
procedure TMyClass1.Shoot;
begin
WriteLn('TMyClass1.Shoot');
end;
procedure TMyClass2.Shoot;
begin
WriteLn('TMyClass2.Shoot');
end;
procedure TMyClass3.Shoot;
begin
WriteLn('TMyClass3.Shoot');
end;
procedure UseThroughInterface(I: IMyInterface);
begin
Write('Shooting... ');
I.Shoot;
end;
var
C1: IMyInterface; // COM takes care of destruction
C2: IMyInterface; // COM takes care of destruction
C3: TMyClass3; // YOU have to take care of destruction
begin
C1 := TMyClass1.Create as IMyInterface;
C2 := TMyClass2.Create as IMyInterface;
101
Modern Object Pascal Introduction for Programmers
C3 := TMyClass3.Create;
try
UseThroughInterface(C1); // no need to use "as" operator
UseThroughInterface(C2);
if C3 is IMyInterface then
UseThroughInterface(C3 as IMyInterface); // this will not execute
finally
{ C1 and C2 variables go out of scope and will be auto-destroyed now.
In contrast, C3 is a class instance, not managed by an interface,
and it has to be destroyed manually. }
FreeAndNil(C3);
end;
end.
10.5. Using COM interfaces with reference-counting disabled
in
the previous section, your class can descend
As mentioned
from
TComponent (or a similar class like TNonRefCountedInterfacedObject and
TNonRefCountedInterfacedPersistent ) which disables reference-counting for
COM interfaces. This allows you to use COM interfaces, and still free the class instance
manually.
You need to be careful in this case to not free the class instance when some interface
variable may refer to it. Remember that every typecast Cx as IMyInterface also
creates a temporary interface variable, which may be present even until the end of
the current procedure. For this reason, the example below uses a UseInterfaces
procedure, and it frees the class instances outside of this procedure (when we can be
sure that temporary interface variables are out of scope).
To avoid this mess, it’s usually better to use CORBA interfaces, if you don’t want
reference-counting with your interfaces.
{$mode objfpc}{$H+}{$J-}
{$interfaces com}
uses
SysUtils, Classes;
type
IMyInterface = interface
['{3075FFCD-8EFB-4E98-B157-261448B8D92E}']
procedure Shoot;
102
Modern Object Pascal Introduction for Programmers
end;
TMyClass1 = class(TComponent, IMyInterface)
procedure Shoot;
end;
TMyClass2 = class(TComponent, IMyInterface)
procedure Shoot;
end;
TMyClass3 = class(TComponent)
procedure Shoot;
end;
procedure TMyClass1.Shoot;
begin
WriteLn('TMyClass1.Shoot');
end;
procedure TMyClass2.Shoot;
begin
WriteLn('TMyClass2.Shoot');
end;
procedure TMyClass3.Shoot;
begin
WriteLn('TMyClass3.Shoot');
end;
procedure UseThroughInterface(I: IMyInterface);
begin
Write('Shooting... ');
I.Shoot;
end;
var
C1: TMyClass1;
C2: TMyClass2;
C3: TMyClass3;
procedure UseInterfaces;
begin
if C1 is IMyInterface then
//if Supports(C1, IMyInterface) then // equivalent to "is" check above
UseThroughInterface(C1 as IMyInterface);
103
Modern Object Pascal Introduction for Programmers
if C2 is IMyInterface then
UseThroughInterface(C2 as IMyInterface);
if C3 is IMyInterface then
UseThroughInterface(C3 as IMyInterface);
end;
begin
C1 := TMyClass1.Create(nil);
C2 := TMyClass2.Create(nil);
C3 := TMyClass3.Create(nil);
try
UseInterfaces;
finally
FreeAndNil(C1);
FreeAndNil(C2);
FreeAndNil(C3);
end;
end.
10.6. Typecasting interfaces
This section applies to both CORBA and COM interfaces (however, it has some explicit
exceptions for CORBA).
1. Casting to an interface type using the as operator makes a check at run-time.
Consider this code:
UseThroughInterface(Cx as IMyInterface);
It works for all C1 , C2 , C3 instances in the examples in previous sections. If
executed, it would make a run-time error in case of C3 , that does not implement
IMyInterface .
Using as operator works consistently regardless if Cx is declared as a class
instance (like TMyClass2 ) or interface (like IMyInterface2 ).
However, it is not allowed for CORBA interfaces.
2. You can instead cast the instance as an interface implicitly:
UseThroughInterface(Cx);
104
Modern Object Pascal Introduction for Programmers
In this case, the typecast must be valid at compile-time. So this will compile for C1
and C2 (that are declared as classes that implement IMyInterface ). But it will
not compile for C3 .
In essence, this typecast looks and works just like for regular classes. Wherever
an instance of a class TMyClass is required, you can always use there a variable
that is declared with a class of TMyClass , or TMyClass descendant. The same
rule applies to interfaces. No need for any explicit typecast in such situations.
3. You can also typecast using IMyInterface(Cx) . Like this:
UseThroughInterface(IMyInterface(Cx));
Usually, such typecasting syntax indicates an unsafe, unchecked typecast. Bad
things will happen if you cast to an incorrect interface. And that’s true, if you cast a
class to a class, or an interface to an interface, using this syntax.
There is a small exception here: if Cx is declared as a class (like TMyClass2 ),
then this is a typecast that must be valid at compile-time. So casting a class to an
interface this way is a safe, fast (checked at compile-time) typecast.
To test it all, play around with this example code:
{$mode objfpc}{$H+}{$J-}
// {$interfaces corba} // note that "as" typecasts for CORBA will not
compile
uses Classes;
type
IMyInterface = interface
['{7FC754BC-9CA7-4399-B947-D37DD30BA90A}']
procedure One;
end;
IMyInterface2 = interface(IMyInterface)
['{A72B7008-3F90-45C1-8F4C-E77C4302AA3E}']
procedure Two;
end;
IMyInterface3 = interface(IMyInterface2)
105
Modern Object Pascal Introduction for Programmers
['{924BFB98-B049-4945-AF17-1DB08DB1C0C5}']
procedure Three;
end;
TMyClass = class(TComponent, IMyInterface)
procedure One;
end;
TMyClass2 = class(TMyClass, IMyInterface, IMyInterface2)
procedure One;
procedure Two;
end;
procedure TMyClass.One;
begin
Writeln('TMyClass.One');
end;
procedure TMyClass2.One;
begin
Writeln('TMyClass2.One');
end;
procedure TMyClass2.Two;
begin
Writeln('TMyClass2.Two');
end;
procedure UseInterface2(const I: IMyInterface2);
begin
I.One;
I.Two;
end;
procedure UseInterface3(const I: IMyInterface3);
begin
I.One;
I.Two;
I.Three;
end;
var
My: IMyInterface;
MyClass: TMyClass;
begin
106
Modern Object Pascal Introduction for Programmers
My := TMyClass2.Create(nil);
MyClass := TMyClass2.Create(nil);
// This doesn't compile, since at compile-time it's unknown if My is
IMyInterface2.
// UseInterface2(My);
// UseInterface2(MyClass);
// This compiles and works OK.
UseInterface2(IMyInterface2(My));
// This does not compile. Casting InterfaceType(ClassType) is checked at
compile-time.
// UseInterface2(IMyInterface2(MyClass));
// This compiles and works OK.
UseInterface2(My as IMyInterface2);
// This compiles and works OK.
UseInterface2(MyClass as IMyInterface2);
// This compiles, but will fail at runtime, with ugly "Access
violation".
// UseInterface3(IMyInterface3(My));
// This does not compile. Casting InterfaceType(ClassType) is checked at
compile-time.
// UseInterface3(IMyInterface3(MyClass));
// This compiles, but will fail at runtime, with nice "EInvalidCast:
Invalid type cast".
// UseInterface3(My as IMyInterface3);
// This compiles, but will fail at runtime, with nice "EInvalidCast:
Invalid type cast".
// UseInterface3(MyClass as IMyInterface3);
Writeln('Finished');
end.
11. About this document
Copyright Michalis Kamburelis.
The source code of this document is in AsciiDoc on https://github.com/michaliskambi/
modern-pascal-introduction. Suggestions for corrections and additions, and patches
and pull requests, are always very welcome:) You can reach me through GitHub
107
Modern Object Pascal Introduction for Programmers
or email michalis@castle-engine.io 4. My homepage is https://michalis.xyz/. This
document is linked under the Documentation section of the Castle Game Engine
website https://castle-engine.io/.
You can redistribute and even modify this document freely, under the same licenses
as Wikipedia https://en.wikipedia.org/wiki/Wikipedia:Copyrights :
• Creative Commons Attribution-ShareAlike 3.0 Unported License (CC BY-SA)
• or the GNU Free Documentation License (GFDL) (unversioned, with no invariant
sections, front-cover texts, or back-cover texts) .
Thank you for reading!
4
mailto:michalis@castle-engine.io
108
|