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.
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.
TypeChildClass = Class(ParentClass)Constructor Create(VARIABLE : ParentClass); override;end;Constructor ChildClass.Create(VARIABLE : ParentClass);begininherited;// Do more thingsend;
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;typeParentClass = classprocedure Method1;virtual;end;ChildClass = class(ParentClass)procedure Method1;override;procedure Method2;end;procedure ParentClass.Method1;beginWriteln('Method1 from parent class');end;procedure ChildClass.Method1;beginWriteln('Method1 from child class');end;procedure ChildClass.Method2;beginMethod1; // this is from the child classinherited Method1; //this is from the parent classend;varExample: ChildClass;beginExample := ChildClass.Create;tryExample.Method2;finally FreeAndNil(Example) end;end.
Free Resources