Key Takeaways — Chapter 16: Introduction to Object-Oriented Programming
The Big Idea
Object-oriented programming is a way of organizing code around objects — self-contained units that bundle data (fields) and behavior (methods) together. Instead of asking "what steps do I perform?" you ask "what things exist in my problem, and what can they do?" This shift in perspective is the threshold concept of this chapter.
Core Concepts
1. Classes and Objects
- A class is a blueprint that defines fields and methods.
- An object (instance) is a concrete realization of a class, living in heap memory.
- In Object Pascal, all classes implicitly descend from
TObject. - Convention: class names start with
T(e.g.,TStudent).
2. Fields and Methods
- Fields hold an object's data (like record fields).
- Methods are procedures and functions that belong to a class.
- Method implementations use the
TClassName.MethodNameprefix. - Methods can directly access the object's fields without extra parameters.
3. Creating and Freeing Objects
- Declare:
var Obj: TMyClass;— creates a reference (pointer), initiallynil. - Create:
Obj := TMyClass.Create(...)— allocates and initializes the object on the heap. - Free:
Obj.Free;— calls the destructor and releases heap memory. - Always use
try...finallyto ensureFreeis called, even if an exception occurs. - Forgetting to free an object causes a memory leak.
4. Constructors and Destructors
- Constructor:
constructor Create(...)— initializes the object. Callinherited Createfirst. - Destructor:
destructor Destroy; override;— cleans up resources. Callinherited Destroylast. - The constructor is where you open files, allocate structures, validate initial state.
- The destructor is where you close files, free owned objects, release resources.
5. Encapsulation and Visibility
- Private: accessible within the class (and same unit in default FPC mode).
- Protected: accessible within the class and descendant classes.
- Public: accessible from anywhere.
- Design principle: make everything as private as possible. Promote visibility only when needed.
6. Properties
- Provide field-like syntax with method-level control.
- Read-only:
property Name: string read FName; - Read-write with validation:
property Grade: Integer read FGrade write SetGrade; - Enable validation, computation, and logging without changing the external interface.
7. Reference Semantics vs. Value Semantics
- Records use value semantics: assignment copies all data.
- Classes use reference semantics: assignment copies the reference (pointer), not the object.
- Two class variables can point to the same object (aliasing).
- Freeing an object through one variable makes all other references dangling.
8. Self
Selfis an implicit reference to the current object inside a method.- Usually implicit — you write
FName, notSelf.FName. - Explicit use: passing the current object to another method, disambiguating names, method chaining.
Patterns to Remember
| Pattern | Code |
|---|---|
| Create and free safely | Obj := T.Create; try ... finally Obj.Free; end; |
| Validate in setter | procedure T.SetX(V); begin if Invalid then raise ...; FX := V; end; |
| Constructor calls inherited first | constructor T.Create; begin inherited Create; ... end; |
| Destructor calls inherited last | destructor T.Destroy; begin ...; inherited Destroy; end; |
| Read-only property | property X: T read FX; |
| Read-write property with setter | property X: T read FX write SetX; |
Common Mistakes to Avoid
-
Using a class variable before calling Create. The variable is
niluntil you create an object. Accessing anilreference causes an access violation. -
Forgetting to free objects. Every
Createneeds a matchingFree. Usetry...finally. -
Double-freeing. If two variables reference the same object and you free it through both, the second
Freecrashes. After freeing, set the variable tonil. -
Assuming assignment copies the object.
B := Afor classes copies the reference, not the object. Changes throughBaffectAand vice versa. -
Making fields public. Public fields bypass validation. Use private fields with properties.
-
Forgetting
inheritedin constructors/destructors. Always callinherited Createfirst in constructors andinherited Destroylast in destructors. -
Forgetting
overrideon Destroy. The destructor must be declared withoverridebecauseDestroyis virtual inTObject.
How This Connects
| Previous Chapters | This Chapter | Next Chapters |
|---|---|---|
| Records group data (Ch 11) | Classes group data and behavior | Inheritance extends classes (Ch 17) |
| Procedures operate on data (Ch 7-8) | Methods belong to objects | Polymorphism varies behavior (Ch 17) |
| Pointers are heap references (Ch 14) | Objects are heap-allocated, accessed by reference | Interfaces define contracts (Ch 18) |
| Scope controls visibility (Ch 8) | Visibility specifiers control access | Abstract classes enforce structure (Ch 18) |
One Sentence Summary
A class is a blueprint that bundles data and behavior into a self-contained unit; an object is a live instance of that blueprint on the heap, created with Create, accessed through references, protected by encapsulation, and freed with Free.