[fpc-pascal] Clone a instance of object
patspiper
patspiper at gmail.com
Mon Sep 23 09:16:45 CEST 2013
On 23/09/13 10:02, Michael Van Canneyt wrote:
>
>
> This is wrong. You are typecasting a class reference to an object
> instance.
>
> The following works:
>
> {$mode objfpc}
>
> Type
> TBaseObject = class(TObject)
> public
> constructor Create; virtual;
> function Clone:TBaseObject;
> end;
> TBaseObjectClass = Class of TBaseObject;
>
> constructor TBaseObject.Create;
>
> begin
> end;
>
> Function TBaseObject.Clone:TBaseObject;
>
> Var
> C : TBaseObjectClass;
> begin
> C:=TBaseObjectClass(ClassType);
> Result:=C.Create;
> end;
What would happen if Result := Self.ClassType.Create were used instead?
>
> Type
> TMyObject = class(TBaseObject)
> // my fields here
> end;
>
> Var
> o1, o2:TmyObject;
>
> begin
> o1:=TMyObject.Create;
> o2 := o1.Clone as TmyObject;
> end.
Stephano
More information about the fpc-pascal
mailing list