DMarlon Studio

Lesson 3 · 3 of 20

Inheritance and inherited · Pascal

Build child classes in Object Pascal that inherit fields and methods, and call the parent constructor with inherited in Free Pascal.

Pascal · Inheritance and inherited in DMarlon Studio: the example's code and its output in the terminal

Inheritance builds one class on top of another. TManager = class(TEmployee) receives everything in TEmployee (the Name and Salary fields and the Print method) and only adds what is new: the Team field and its own constructor.

TManager's constructor does not redo its parent's work: `inherited Create(AName, ASalary)` calls TEmployee's constructor, which fills in the name and salary, and then all that is left is storing Team. Calling inherited first thing in a constructor is the usual pattern.

boss.Print works even though TManager declares no Print: it is looked up in the parent class. That is why the first output line is written by TEmployee code using a TManager's data.

The `is` operator checks whether an object belongs to a class or any of its descendants, and returns TRUE for boss is TEmployee: a manager is also an employee. ClassName returns the object's real class name, TManager.

Every class ultimately descends from TObject, which is where Create, Free and ClassName come from. In Lazarus you see it in every window: TForm1 = class(TForm) inherits everything a form can do and you only add your own parts.

Code · main.pas

program main;type  TEmployee = class    Name: String;    Salary: Double;    constructor Create(const AName: String; ASalary: Double);    procedure Print;  end;  TManager = class(TEmployee)  // inherits Name, Salary and Print    Team: Integer;    constructor Create(const AName: String; ASalary: Double; ATeam: Integer);  end;constructor TEmployee.Create(const AName: String; ASalary: Double);begin  Name := AName; Salary := ASalary;end;procedure TEmployee.Print;begin  WriteLn(Name, ' earns ', Salary:0:0, ' EUR a month');end;constructor TManager.Create(const AName: String; ASalary: Double; ATeam: Integer);begin  inherited Create(AName, ASalary);  // the parent fills Name and Salary  Team := ATeam;end;var boss: TManager;begin  boss := TManager.Create('Javier Ruiz', 3600, 5);  boss.Print;  // a TEmployee method  WriteLn(boss.ClassName, ' leads ', boss.Team, ' people; is a TEmployee: ', boss is TEmployee);  boss.Free;end.

Output · fpc main.pas && ./main

Javier Ruiz earns 3600 EUR a month
TManager leads 5 people; is a TEmployee: TRUE

Key points

  • class(TParent) inherits fields and methods.
  • The child class only declares what it adds or changes.
  • inherited Create(...) reuses the parent constructor.
  • is checks the class, descendants included.
  • Every class descends from TObject.

Exercise

Create TSalesRep = class(TEmployee) with a Commission: Double field (say 0.05) and a constructor that uses inherited, and print its salary plus the commission on 20000 EUR of sales.