Quick start manual

7-24
Delphi Language Guide
Class references
can cast MyObject to TDescendant to access the descendant class’s properties and their
access specifiers.
type
TAncestor = class
ƒ
property Value: Integer read Method1 write Method2;
end;
TDescendant = class(TAncestor)
ƒ
property Value: Integer read Method3 write Method4;
end;
var MyObject: TAncestor;
ƒ
MyObject := TDescendant.Create;
Class references
Sometimes operations are performed on a class itself, rather than on instances of a
class (that is, objects). This happens, for example, when you call a constructor method
using a class reference. You can always refer to a specific class using its name, but at
times it is necessary to declare variables or parameters that take classes as values, and
in these situations you need class-reference types.
Class-reference types
A class-reference type, sometimes called a metaclass, is denoted by a construction of
the form
class of type
where type is any class type. The identifier type itself denotes a value whose type is
class of type. If type
1
is an ancestor of type
2
, then class of type
2
is assignment-
compatible with class of type
1
. Thus
type TClass = class of TObject;
var AnyObj: TClass;
declares a variable called AnyObj that can hold a reference to any class. (The
definition of a class-reference type cannot occur directly in a variable declaration or
parameter list.) You can assign the value nil to a variable of any class-reference type.
To see how class-reference types are used, look at the declaration of the constructor
for TCollection (in the Classes unit):
type TCollectionItemClass = class of TCollectionItem;
ƒ
constructor Create(ItemClass: TCollectionItemClass);