6.6.8 Using inherited

In an overridden virtual method, it is often necessary to call the parent class’ implementation of the virtual method. This can be done with the inherited keyword. Likewise, the inherited keyword can be used to call any method of the parent class.

The first case is the simplest:

Type  
  TMyClass = Class(TComponent)  
    Constructor Create(AOwner : TComponent); override;  
  end;  
 
Constructor TMyClass.Create(AOwner : TComponent);  
 
begin  
  Inherited;  
  // Do more things  
end;

In the above example, the Inherited statement will call Create of TComponent, passing it AOwner as a parameter: the same parameters that were passed to the current method will be passed to the parent’s method. They must not be specified again: if none are specified, the compiler will pass the same arguments as the ones received.

If no inherited method with the same name exists, the Inherited will have no effect in this case. The presence of Inherited in this form can thus be interpreted as “call the overridden method if it exists”.

The second case is slightly more complicated:

Type  
  TMyClass = Class(TComponent)  
    Constructor Create(AOwner : TComponent); override;  
    Constructor CreateNew(AOwner : TComponent; DoExtra : Boolean);  
  end;  
 
Constructor TMyClass.Create(AOwner : TComponent);  
begin  
  Inherited;  
end;  
 
Constructor TMyClass.CreateNew(AOwner : TComponent; DoExtra : Boolean);  
begin  
  Inherited Create(AOwner);  
  // Do stuff  
end;

The CreateNew method will first call TComponent.Create and will pass it AOwner as a parameter. It will not call TMyClass.Create.

If no method with the given name exists in parent classes, the compiler will give an error.

Although the examples were given using constructors, the use of inherited is not restricted to constructors, it can be used for any procedure or function or destructor as well.