6.3.2 Virtual methods

Classes have virtual methods, just as objects do. There is however a dierence between the two. For objects, it is sucient to redeclare the same method in a descendent object with the keyword virtual to override it. For classes, the situation is dierent: 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 eects.

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.