[fpc-pascal] why (ClassType as TMyClass).Create fails

Michael Van Canneyt michael at freepascal.org
Tue Jun 21 16:09:10 CEST 2016



On Tue, 21 Jun 2016, Dennis wrote:

> Following up to the cloning example code:
>
> Type
> TMyClassRef = class of TMyClass;
>
> implementation
>
> function TMyClass.Clone(AOwner: TComponent): TMyClass;
> begin
>  Result := TMyClassRef(ClassType).Create(AOwner);
>
> //but the next line will fail to compile
> //  Result := (ClassType as TMyClassRef).Create(aOwner);

This should be
   TMyClassRef(ClassType).Create(aOwner);

>  Result.Assign(Self);
> end
>
> Isn't (ClassType as TMyClassRef).Create(aOwner)  supposed to be safer because 
> sometimes we copy and paste code around and in the end  (ClassType might not 
> be a descendant of TMyClass and the compiler won't catch this type mismatch 
> if we do
>
>  Result := TMyClassRef(ClassType).Create(AOwner);
>
> Am I missing something?

No, this construct is not supported.

Michael.



More information about the fpc-pascal mailing list