Quick start manual

Classes and objects
7-25
Class references
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.
Constructors and class references
A constructor can be called using a variable of a class-reference type. This allows
construction of objects whose type isn’t known at compile time. For example,
type TControlClass = class of TControl;
function CreateControl(ControlClass: TControlClass;
const ControlName: string; X, Y, W, H: Integer): TControl;
begin
Result := ControlClass.Create(MainForm);
with Result do
begin
Parent := MainForm;
Name := ControlName;
SetBounds(X, Y, W, H);
Visible := True;
end;
end;
The CreateControl function requires a class-reference parameter to tell it what kind of
control to create. It uses this parameter to call the class’s constructor. Because class-
type identifiers denote class-reference values, a call to CreateControl can specify the
identifier of the class to create an instance of. For example,
CreateControl(TEdit, 'Edit1', 10, 10, 100, 20);
Constructors called using class references are usually virtual. The constructor
implementation activated by the call depends on the runtime type of the class
reference.
Class operators
Every class inherits from TObject methods called ClassType and ClassParent that
return, respectively, a reference to the class of an object and of an object’s immediate
ancestor. Both methods return a value of type TClass (where TClass = class of
TObject), which can be cast to a more specific type. Every class also inherits a method
called InheritsFrom that tests whether the object where it is called descends from a
specified class. These methods are used by the is and as operators, and it is seldom
necessary to call them directly.