Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Classes and Properties

Inheritance and Virtual Methods

Build class hierarchies in Object Pascal with inherited, virtual and override, abstract classes, is and as type tests, and see how a virtual method table works in C.

Inheritance lets a new class start from an existing one and add or change behavior. A TCircle and a TSquare are both shapes: they share a color and a name, but compute their area differently. With inheritance you write the shared part once, in a base class, and each shape supplies its own area.

The key feature that makes this useful is polymorphism: code that holds a TShape reference can call Area, and the right version runs for whatever object is actually there. In Object Pascal that requires two keywords, virtual and override.

Deriving a class

Name the parent in parentheses. If you name none, the class derives from TObject, the root of every class:

PASCAL
type
  TShape = class
  strict private
    FName: string;
  public
    constructor Create(const AName: string);
    function Area: Double; virtual;
    function Describe: string;
    property Name: string read FName;
  end;

  TCircle = class(TShape)
  strict private
    FRadius: Double;
  public
    constructor Create(ARadius: Double);
    function Area: Double; override;
  end;

  TRectangle = class(TShape)
  strict private
    FWidth, FHeight: Double;
  public
    constructor Create(AWidth, AHeight: Double);
    function Area: Double; override;
  end;

A descendant gets every field, method and property of its ancestors, and can use them as its own. TCircle has a Name, a Describe and an Area, even though it wrote only the radius and its own Area.

inherited

A descendant's constructor should normally call the parent's constructor first with inherited, so the base part is set up:

PASCAL
constructor TCircle.Create(ARadius: Double);
begin
  inherited Create('circle');
  FRadius := ARadius;
end;

function TShape.Area: Double;
begin
  Result := 0;
end;

function TCircle.Area: Double;
begin
  Result := Pi * FRadius * FRadius;
end;

function TShape.Describe: string;
begin
  Result := Format('%s with area %.2f', [Name, Area]);
end;

Writing just inherited; (no name) calls the parent version of the current method with the same arguments. It is common in overridden methods that want to extend rather than replace the parent's work.

virtual, override and the vtable

A method declared virtual in the base class can be replaced in a descendant with override. When you call it through a base-class variable, the version belonging to the actual object runs:

PASCAL
var
  Shapes: TObjectList<TShape>;
  S: TShape;
begin
  Shapes := TObjectList<TShape>.Create;   // owns its objects
  try
    Shapes.Add(TCircle.Create(2));
    Shapes.Add(TRectangle.Create(3, 4));
    for S in Shapes do
      WriteLn(S.Describe);
  finally
    Shapes.Free;
  end;
end;

Describe is not virtual, yet it prints the right area: it calls Area, and Area is virtual, so the call is dispatched on the real class. Each class has a virtual method table (VMT): an array of code addresses, one per virtual method. Each object begins with a hidden pointer to its class's table. A virtual call reads that pointer, finds the slot, and jumps there.

If you forget virtual, a method with the same name in the descendant only hides the parent's version. The compiler warns that it "hides virtual method of base type" or, for static methods, simply binds by the declared type, which defeats polymorphism. If you really mean to hide, say so with reintroduce.

Abstract methods and classes

A method can be virtual; abstract; with no body: it exists only to be overridden.

PASCAL
type
  TShape = class
  public
    function Area: Double; virtual; abstract;
  end;

Calling an abstract method on an object whose class did not override it raises the runtime error "Abstract Error". Delphi also lets you mark a class itself abstract (a class that you should not create directly, with class abstract). Abstract methods document what every descendant must provide.

Testing and casting types: is and as

PASCAL
if S is TCircle then
  WriteLn(TCircle(S).Area:0:2);                // unchecked cast

C := S as TCircle;                                // raises EInvalidCast if wrong
if S is TCircle then C := TCircle(S);             // is test, then cast: fastest

is returns true when the object's class is the given class or a descendant. as casts and raises EInvalidCast if the object is not of that type. Heavy use of is chains is a sign the design should use a virtual method instead.

Other useful details

  • TObject.ClassName returns the class's name as a string, handy for logging.
  • Self.ClassType and ClassParent let you walk up the hierarchy at run time.
  • final (in recent Delphi) stops a method from being overridden again, and sealed stops a class from being inherited.
  • Every class is a descendant of TObject, which gives you Create, Free, ClassName, ToString, Equals, GetHashCode.

A vtable in C

C has no inheritance, but the machinery underneath is just structs and function pointers. Here a "base class" holds a pointer to its table of virtual methods. Each "derived class" fills in its own table. Describe calls through the table, so it works with any shape.

C Stand-in: a virtual method table by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The describe function never mentions circles or rectangles, yet each shape reports its own area. That is polymorphism, and it costs one extra pointer read per call.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which keyword pair makes a method polymorphic?

    virtual marks the method for dynamic dispatch and override replaces it in a descendant.
  2. 2. What does inherited Create('circle'); do inside a descendant constructor?

    The base class needs to initialize its fields too, so the descendant calls its constructor first.
  3. 3. What happens when S as TCircle is evaluated and S is a TRectangle?

    as performs a checked cast and raises EInvalidCast for a wrong type.
  4. 4. What is a virtual method table?

    Each object points to its class's table, so a virtual call finds the right code for the real class.

Summary

  • A descendant class inherits everything from its parent; TObject is the root.
  • Call inherited to run the parent's version of a method or constructor.
  • virtual plus override gives polymorphism through the class's virtual method table.
  • abstract methods have no body and must be overridden; reintroduce hides on purpose.
  • is tests a type; as casts with a check. Prefer virtual methods over long is chains.

Next: Interfaces and Exceptions