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.
This topic covers the following material:
Class reference types
Class operators
Class methods
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
type1
is
an ancestor of
type2
, then
class of type2
is assignment-compatible with class of
type1
. 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);
This declaration says that to create a TCollection instance object, you must pass to the constructor the name of a
class descending from TCollectionItem.
Class-reference types are useful when you want to invoke a class method or virtual constructor on a class or object
whose actual type is unknown at compile time.