What is inherited in Pascal classes?

Overview

The inherited keyword is used to call methods of the parent class. We will be using examples of parent class constructors to understand different applications of the inherited keyword.

Overridden virtual method

When we have an overridden virtual method, it is important that we call the parent’s virtual method. We can do so using the inherited keyword. As shown below, using the keyword inherited calls the Create method for the ParentClass if such a method exists. Hence, this will only call the overridden method if it exists for the parent class as well.

Type
ChildClass = Class(ParentClass)
Constructor Create(VARIABLE : ParentClass); override;
end;
Constructor ChildClass.Create(VARIABLE : ParentClass);
begin
inherited;
// Do more things
end;

Example

The following example will help you understand the concept of inherited better. As shown above, there is a parent class and a child class. Both classes have a method called Method1.

As Method1 is a virtual method, the child class uses the override keyword in its definition. Method2 in the child class demonstrates how Method1 behaves differently with and without the inherited keyword.

When Method1 is called from the child class, it prints the implementation of the child class, whereas, with the inherited keyword, the second print demonstrates that the Method1 implemented was of the parent class.

Moreover, in the implementation of Method1 in the child class, if we simply wrote inherited;, the method would print the parent class implementation of Method1 regardless of using the keyword inherited in Method2.

{$mode objfpc}{$H+}{$J-}
uses SysUtils;
type
ParentClass = class
procedure Method1;virtual;
end;
ChildClass = class(ParentClass)
procedure Method1;override;
procedure Method2;
end;
procedure ParentClass.Method1;
begin
Writeln('Method1 from parent class');
end;
procedure ChildClass.Method1;
begin
Writeln('Method1 from child class');
end;
procedure ChildClass.Method2;
begin
Method1; // this is from the child class
inherited Method1; //this is from the parent class
end;
var
Example: ChildClass;
begin
Example := ChildClass.Create;
try
Example.Method2;
finally FreeAndNil(Example) end;
end.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved