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.MethodName prefix.
  • Methods can directly access the object's fields without extra parameters.

3. Creating and Freeing Objects

  • Declare: var Obj: TMyClass; — creates a reference (pointer), initially nil.
  • 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...finally to ensure Free is 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. Call inherited Create first.
  • Destructor: destructor Destroy; override; — cleans up resources. Call inherited Destroy last.
  • 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

  • Self is an implicit reference to the current object inside a method.
  • Usually implicit — you write FName, not Self.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

  1. Using a class variable before calling Create. The variable is nil until you create an object. Accessing a nil reference causes an access violation.

  2. Forgetting to free objects. Every Create needs a matching Free. Use try...finally.

  3. Double-freeing. If two variables reference the same object and you free it through both, the second Free crashes. After freeing, set the variable to nil.

  4. Assuming assignment copies the object. B := A for classes copies the reference, not the object. Changes through B affect A and vice versa.

  5. Making fields public. Public fields bypass validation. Use private fields with properties.

  6. Forgetting inherited in constructors/destructors. Always call inherited Create first in constructors and inherited Destroy last in destructors.

  7. Forgetting override on Destroy. The destructor must be declared with override because Destroy is virtual in TObject.


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.