what is the meaning of `Class of ` type declaration?

c++builder, class, delphi, delphi-xe

Solution

This is a Class Reference.

They are used to work with meta classes. The canonical example is the Delphi streaming framework which uses

TComponentClass = class of TComponent;

This allows for dynamic binding to virtual constructors. The `TComponent` constructor is `virtual`. The streaming framework needs to instantiate classes derived from `TComponent`. It does so something like this:

var
  ComponentClass: TComponentClass;
  Component: TComponent;
....
ComponentClass := GetComponentClassSomehowDoesntMatterHow;
Component := ComponentClass.Create(Owner);

Now, because `TComponent.Create` is `virtual`, this is bound in a polymorphic fashion. If `TComponentClass` is `TButton`, then `TButton.Create` is called. If `TComponentClass` is `TPanel`, then `TPanel.Create` is called. And so on.

The most important thing to realise is that the class that is constructed is determined only at runtime. Note that many languages lack this capability, most notably C++.

Problem

While going through one of my code, I am stuck on one statement which is as below. `TMyObjectClass = class of TMyObject;` I am a bit confused, and wondering what is the meaning of this statement. As `TMyObjectClass` has no declaration above the statement. and `TMyObject` is having declaration as below: `TMyObject = class(TObject) private //some private member declaration Public // some public variables end;` So, my question is what is the meaning of the statement `TMyObjectClass = class of TMyObject;` and How `TMyObjectClass` works? I am a bit new to Delphi, so please help me to get some idea about these type of declaration and there workarounds.

Original source