Quick start manual
Classes and objects
7-11
Methods
Virtual and dynamic methods
To make a method virtual or dynamic, include the virtual or dynamic directive in its
declaration. Virtual and dynamic methods, unlike static methods, can be overridden in
descendant classes. When an overridden method is called, the actual (runtime) type
of the class or object used in the method call—not the declared type of the variable—
determines which implementation to activate.
To override a method, redeclare it with the override directive. An override
declaration must match the ancestor declaration in the order and type of its
parameters and in its result type (if any).
In the following example, the Draw method declared in TFigure is overridden in two
descendant classes.
type
TFigure = class
procedure Draw; virtual;
end;
TRectangle = class(TFigure)
procedure Draw; override;
end;
TEllipse = class(TFigure)
procedure Draw; override;
end;
Given these declarations, the following code illustrates the effect of calling a virtual
method through a variable whose actual type varies at runtime.
var
Figure: TFigure;
begin
Figure := TRectangle.Create;
Figure.Draw; // calls TRectangle.Draw
Figure.Destroy;
Figure := TEllipse.Create;
Figure.Draw; // calls TEllipse.Draw
Figure.Destroy;
end;
Only virtual and dynamic methods can be overridden. All methods, however, can be
overloaded; see “Overloading methods” on page 7-12.
Virtual versus dynamic
Virtual and dynamic methods are semantically equivalent. They differ only in the
implementation of method-call dispatching at runtime. Virtual methods optimize for
speed, while dynamic methods optimize for code size.
In general, virtual methods are the most efficient way to implement polymorphic
behavior. Dynamic methods are useful when a base class declares many overridable
methods which are inherited by many descendant classes in an application, but only
occasionally overridden.
Note
Only use dynamic methods if there is a clear, observable benefit. Generally, use
virtual methods.