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

Dennis dec12 at avidsoft.com.hk
Tue Jun 21 15:57:16 CEST 2016


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);
   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?

Dennis



More information about the fpc-pascal mailing list