What are virtual methods in Pascal classes?

Overview

Virtual methods are declared using the virtual keyword in Pascal. It is a method for classes that allow them to be overridden by the child class method with the same class signature. In Pascal, it is mandatory to use the keyword override to implement polymorphism. We use the keyword virtual so the method can be overridden.

Examples

Declaring virtual methods

The following example will give you a general idea of how you should declare a virtual method:

{$mode objfpc}
Type  
  Parent = Class  
    Procedure Func; virtual;  
  end;  
  Child  = Class(Parent)  
    Procedure Func; override;  
  end;

There are two classes, and the child class is derived from the parent class. The override keyword will be used for the child class method.

Using reintroduce

Rather than overriding a virtual method, if you wish to replace a virtual method with a new method of the same signature, you can use the reintroduce keyword instead.

{$mode objfpc}
Type  
  Parent = Class  
    Procedure Func; virtual;  
  end;  
  Child  = Class(Parent)  
    Procedure Func; reintroduce;  
  end;

Procedure Func is no longer a virtual method.

In Pascal, the compiler keeps a list of virtual methods. When a derived class overrides the virtual method in this list, the virtual method is overridden and the parent class method is overwritten in the list.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved