6.6.4 Virtual methods

Classes have virtual methods, just as objects do. There is however a difference between the two. For objects, it is sufficient to redeclare the same method in a descendent object with the keyword virtual to override it. For classes, the situation is different: virtual methods must be overridden with the override keyword. Failing to do so, will start a new batch of virtual methods, hiding the previous one. The Inherited keyword will not jump to the inherited method, if Virtual was used.

The following code is wrong:

Type
  ObjParent = Class
    Procedure MyProc; virtual;
  end;
  ObjChild  = Class(ObjPArent)
    Procedure MyProc; virtual;
  end;

The compiler will produce a warning:

Warning: An inherited method is hidden by OBJCHILD.MYPROC

The compiler will compile it, but using Inherited can produce strange effects.

The correct declaration is as follows:

Type
  ObjParent = Class
    Procedure MyProc; virtual;
  end;
  ObjChild  = Class(ObjPArent)
    Procedure MyProc; override;
  end;

This will compile and run without warnings or errors.

If the virtual method should really be replaced with a method with the same name, then the reintroduce keyword can be used:

Type
  ObjParent = Class
    Procedure MyProc; virtual;
  end;
  ObjChild  = Class(ObjPArent)
    Procedure MyProc; reintroduce;
  end;

This new method is no longer virtual.

To be able to do this, the compiler keeps – per class type – a table with virtual methods: the VMT (Virtual Method Table). This is simply a table with pointers to each of the virtual methods: each virtual method has its fixed location in this table (an index). The compiler uses this table to look up the actual method that must be used at runtime. When a descendent object overrides a method, the entry of the parent method is overwritten in the VMT. More information about the VMT can be found in Programmer’s Guide.

Remark The keyword “virtual” can be replaced with the “dynamic” keyword: dynamic methods behave the same as virtual methods. Unlike in Delphi, in FPC the implementation of dynamic methods is equal to the implementation of virtual methods.