_________________________________________________________________________________________________________
Class types







___________________________________________________________________
As many private, protected, published and public blocks as needed can be repeated. Methods are normal function or procedure declarations. As can be seen, the declaration of a class is almost identical to the declaration of an object. The real di erence between objects and classes is in the way they are created (see further in this chapter). The visibility of the di erent sections is as follows:
In the syntax diagram, it can be seen that a class lists implemented interfaces. This will be discussed in the next chapter.
It is also possible to de ne class reference types:
_________________________________________________________________________________________________________
Class reference type

___________________________________________________________________
Class reference types are used to create instances of a certain class, which is not yet known at compile time, but which is speci ed at run time. Essentially, a variable of a class reference type contains a pointer to the de nition of the spe cied class. This can be used to construct an instance of the class corresponding to the de nition, or to check inheritance. The following example shows how it works:
Type
TComponentClass = Class of TComponent; Function CreateComponent(AClass : TComponentClass; AOwner : TComponent) : TComponent; begin // ... Result:=AClass.Create(AOwner); // ... end; |
This function can be passed a class reference of any class that descends from TComponent. The following is a valid call:
Var
C : TComponent; begin C:=CreateComponent(TEdit,Form1); end; |
On return of the CreateComponent function, C will contain an instance of the class TEdit. Note that the following call will fail to compile:
Var
C : TComponent; begin C:=CreateComponent(TStream,Form1); end; |
because TStream does not descend from TComponent, and AClass refers to a TComponent class. The compiler can (and will) check this at compile time, and will produce an error.
References to classes can also be used to check inheritance:
TMinClass = Class of TMyClass;
TMaxClass = Class of TMyClassChild; Function CheckObjectBetween(Instance : TObject) : boolean; begin If not (Instance is TMinClass) or ((Instance is TMaxClass) and (Instance.ClassType<>TMaxClass)) then Raise Exception.Create(SomeError) end; |
The above example will More about instantiating a class can be found in the next section.