ZetCode

Pascal inheritance and polymorphism

last modified November 19, 2026 Free Pascal 3.2.2

Inheritance lets one class extend another. The descendant receives the fields and methods of its ancestor, can add new ones, and can replace a method with its own implementation. When the replaced method is virtual, the call is resolved from the actual object at run time rather than from the variable type, which is polymorphism. This article starts with one child class, then adds overriding, abstract methods, polymorphic arrays, inherited calls, type tests, and class references.

A child class

A descendant is declared with the ancestor in parentheses after the class name. TDog = class(TAnimal) means that every TDog is also a TAnimal: it has the Name field and may add methods of its own. The ancestor is also called the base or parent class, and the descendant the derived or child class.

child.pas
program child;
{$mode objfpc}{$H+}

type
  TAnimal = class
    Name: string;
  end;

  TDog = class(TAnimal)
    procedure Bark;
  end;

procedure TDog.Bark;
begin
  WriteLn(Name, ' says woof');
end;

var
  Dog: TDog;

begin
  Dog := TDog.Create;
  Dog.Name := 'Rex';
  Dog.Bark;
  Dog.Free;
end.

TDog inherits the Name field without writing it again and adds Bark. The inherited field is part of every dog object, so Bark can read it directly. The constructor is not declared in either class, so both use the parameterless Create inherited from TObject.

$ fpc -gl child.pas
$ ./child
Rex says woof

Overriding a method

A method that a descendant may replace is marked virtual in the ancestor. The descendant repeats the signature and adds override. The call is then dispatched from the actual class of the object, not from the declared type of the variable. Without virtual, the compiler binds the call to the variable's type at compile time.

override1.pas
program override1;
{$mode objfpc}{$H+}

type
  TAnimal = class
  public
    function Speak: string; virtual;
  end;

  TDog = class(TAnimal)
  public
    function Speak: string; override;
  end;

function TAnimal.Speak: string;
begin
  Result := '...';
end;

function TDog.Speak: string;
begin
  Result := 'woof';
end;

var
  A: TAnimal;

begin
  A := TDog.Create;
  WriteLn(A.Speak);
  A.Free;
end.

The variable A has type TAnimal, but it holds a TDog object. A.Speak therefore runs TDog.Speak and prints woof. This is the whole point of virtual methods: one piece of code can work with a base-class reference and still run the most specific implementation. If Speak were not virtual, the same call would print the three dots from TAnimal.

$ fpc -gl override1.pas
$ ./override1
woof

An abstract method

An abstract method has a signature but no body: it is declared virtual; abstract; and every concrete descendant must implement it. The ancestor can still provide ordinary virtual methods for the parts that are shared. A class with an abstract method is meant to be used through a base-class reference, not instantiated directly.

abstract1.pas
program abstract1;
{$mode objfpc}{$H+}

type
  TShape = class
  public
    function Area: Double; virtual; abstract;
    function Name: string; virtual;
  end;

  TCircle = class(TShape)
  private
    FRadius: Double;
  public
    constructor Create(ARadius: Double);
    function Area: Double; override;
    function Name: string; override;
  end;

constructor TCircle.Create(ARadius: Double);
begin
  inherited Create;
  FRadius := ARadius;
end;

function TShape.Name: string;
begin
  Result := 'shape';
end;

function TCircle.Area: Double;
begin
  Result := Pi * FRadius * FRadius;
end;

function TCircle.Name: string;
begin
  Result := 'circle';
end;

var
  S: TShape;

begin
  S := TCircle.Create(2);
  WriteLn(S.Name, ': ', S.Area:0:2);
  S.Free;
end.

TShape declares Area as abstract and supplies a default Name. TCircle implements Area and overrides Name. The variable S has the base type, so the call to Area goes through the virtual method table to the circle implementation. Calling TShape.Create and then Area would stop with runtime error 211, because the abstract slot has no address.

$ fpc -gl abstract1.pas
$ ./abstract1
circle: 12.57

An array of shapes

The real power of a virtual method appears when many descendants are handled by one piece of code. An array of base-class references can hold objects of different descendant classes, and each object answers with its own method. This is polymorphism in its everyday form: the loop does not know which class it is dealing with.

polymorph.pas
program polymorph;
{$mode objfpc}{$H+}

type
  TShape = class
    function Area: Double; virtual; abstract;
  end;

  TCircle = class(TShape)
    Radius: Double;
    constructor Create(ARadius: Double);
    function Area: Double; override;
  end;

  TRectangle = class(TShape)
    Width, Height: Double;
    constructor Create(AWidth, AHeight: Double);
    function Area: Double; override;
  end;

constructor TCircle.Create(ARadius: Double);
begin
  inherited Create;
  Radius := ARadius;
end;

function TCircle.Area: Double;
begin
  Result := Pi * Radius * Radius;
end;

constructor TRectangle.Create(AWidth, AHeight: Double);
begin
  inherited Create;
  Width := AWidth;
  Height := AHeight;
end;

function TRectangle.Area: Double;
begin
  Result := Width * Height;
end;

var
  Shapes: array[1..3] of TShape;
  I: Integer;

begin
  Shapes[1] := TCircle.Create(2);
  Shapes[2] := TRectangle.Create(3, 4);
  Shapes[3] := TCircle.Create(0.5);
  for I := 1 to 3 do
    WriteLn('shape ', I, ': ', Shapes[I].Area:0:2);
  for I := 1 to 3 do
    Shapes[I].Free;
end.

Area is abstract in TShape and implemented by both descendants. The array holds TShape references, yet the loop calls the circle formula for the first and third element and the rectangle formula for the second. Each constructor takes the parameters its class needs and calls inherited Create first. The destructor call is polymorphic too: Free runs the destructor of the actual class, so an object that owns memory can release it even when the variable has the ancestor type.

$ fpc -gl polymorph.pas
$ ./polymorph
shape 1: 12.57
shape 2: 12.00
shape 3: 0.79

Calling inherited methods

A descendant can reuse the ancestor implementation through inherited. Written with a method name, as in inherited Describe, it calls that method in the parent class. Written alone inside a method body, it calls the same method in the parent. The usual places are a constructor that must initialize the ancestor fields and a destructor that must release them.

inherited1.pas
program inherited1;
{$mode objfpc}{$H+}

type
  TAnimal = class
  public
    function Describe: string; virtual;
  end;

  TDog = class(TAnimal)
  public
    function Describe: string; override;
  end;

function TAnimal.Describe: string;
begin
  Result := 'an animal';
end;

function TDog.Describe: string;
begin
  Result := inherited Describe + ' that barks';
end;

var
  D: TDog;

begin
  D := TDog.Create;
  WriteLn(D.Describe);
  D.Free;
end.

TDog.Describe calls the animal version, which returns an animal, and appends its own text. The result is an animal that barks. A constructor that skips inherited Create leaves the ancestor fields uninitialized, and a destructor that skips inherited Destroy leaks whatever the ancestor owns. The convention in the Free Pascal run-time library is that every destructor ends with inherited Destroy.

$ fpc -gl inherited1.pas
$ ./inherited1
an animal that barks

Runtime type checks with is and as

A base-class variable may hold a descendant, and sometimes the code needs to know which one. The is operator tests whether an object is an instance of a class or of one of its descendants. The as operator performs a checked cast: if the object is not compatible with the target type, it raises EInvalidCast. A plain hard cast would skip the check and let the program read the wrong fields.

cast.pas
program cast;
{$mode objfpc}{$H+}

type
  TShape = class
  public
    function Kind: string; virtual;
  end;

  TCircle = class(TShape)
  public
    function Kind: string; override;
    function Radius: Double;
  end;

  TSquare = class(TShape)
  public
    function Kind: string; override;
  end;

function TShape.Kind: string;
begin
  Result := 'shape';
end;

function TCircle.Kind: string;
begin
  Result := 'circle';
end;

function TCircle.Radius: Double;
begin
  Result := 2.5;
end;

function TSquare.Kind: string;
begin
  Result := 'square';
end;

procedure Show(const S: TShape);
var
  C: TCircle;
begin
  Write(S.ClassName, ': kind = ', S.Kind);
  if S is TCircle then
  begin
    C := S as TCircle;
    Write(', radius = ', C.Radius:0:1);
  end;
  WriteLn;
end;

var
  Shapes: array[1..3] of TShape;
  I: Integer;

begin
  Shapes[1] := TShape.Create;
  Shapes[2] := TCircle.Create;
  Shapes[3] := TSquare.Create;
  for I := 1 to 3 do
    Show(Shapes[I]);
  for I := 1 to 3 do
    Shapes[I].Free;
end.

Show receives every object through a TShape parameter. It prints the runtime class name from ClassName, then uses is to decide whether the object has a radius. The cast S as TCircle is safe because the test has already succeeded, and it documents the assumption to the reader. A TSquare fails the test and is printed without the extra field.

$ fpc -gl cast.pas
$ ./cast
TShape: kind = shape
TCircle: kind = circle, radius = 2.5
TSquare: kind = square

Class references and virtual constructors

A class reference is a value that denotes a class rather than an object. The type TShapeClass = class of TShape can hold TShape or any descendant, and calling Create on such a value constructs an object of the class it holds. A constructor called through a class reference must be declared virtual so that the right constructor runs.

factory.pas
program factory;
{$mode objfpc}{$H+}

type
  TShape = class
  public
    constructor Create; virtual;
    function Name: string; virtual; abstract;
  end;

  TCircle = class(TShape)
  public
    constructor Create; override;
    function Name: string; override;
  end;

  TSquare = class(TShape)
  public
    constructor Create; override;
    function Name: string; override;
  end;

  TShapeClass = class of TShape;

constructor TShape.Create;
begin
end;

constructor TCircle.Create;
begin
  inherited Create;
end;

function TCircle.Name: string;
begin
  Result := 'circle';
end;

constructor TSquare.Create;
begin
  inherited Create;
end;

function TSquare.Name: string;
begin
  Result := 'square';
end;

function MakeShape(ShapeClass: TShapeClass): TShape;
begin
  Result := ShapeClass.Create;
end;

var
  Shape: TShape;

begin
  Shape := MakeShape(TCircle);
  WriteLn(Shape.Name);
  Shape.Free;
  Shape := MakeShape(TSquare);
  WriteLn(Shape.Name);
  Shape.Free;
end.

MakeShape takes a class reference and returns a new object of that class. It does not contain a case statement or a list of class names, so a new descendant can be added without changing it. The caller passes the class itself, not an instance. This pattern is the basis of factories, plug-in registries, and object persistence.

$ fpc -gl factory.pas
$ ./factory
circle
square

Designing a class hierarchy

Inheritance models an "is a" relationship: a circle is a shape, a dog is an animal. If the relationship is really "has a" or "uses a", composition is the better tool. A car has an engine; making TCar descend from TEngine would expose every engine method on the car and confuse the type system. The classes article showed an object that owns a TStringList, which is composition in practice.

Keep the ancestor small and its virtual methods meaningful. A deep hierarchy with methods that most descendants ignore is harder to follow than a shallow one with a few well-named operations. Mark methods virtual only when descendants are expected to replace them, and mark classes abstract when they exist only to define an interface. If every descendant must supply a method, make it abstract rather than returning a dummy value that hides a missing implementation.

Next steps

The interfaces article shows how a class can promise several independent contracts without multiple inheritance. The generics article makes container types independent of the element type, and the advanced records article presents the value-type alternative to a class hierarchy.

Source

Free Pascal Reference guide

Free Pascal: classes

Pascal on Wikipedia

In this article we extended a class, overrode a virtual method, declared an abstract method, stored descendants in an array of base-class references, called inherited implementations, tested and cast object types with is and as, and created objects through class references. The series continues with Pascal interfaces.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.