[fpc-pascal] Clone a instance of object

Michael Van Canneyt michael at freepascal.org
Mon Sep 23 09:02:19 CEST 2013



On Mon, 23 Sep 2013, Zaher Dirkey wrote:

> Hi,
> I have objects (classes) derived from base one
> 
> TBaseObject = class(TObject)
> public
>    constructor Create; virtual;
>    function Clone:TBaseObject;
> end;
> 
> TMyObject = class(TBaseObject)
>    my fields here
> end;
> 
> o1, o2:TmyObject;
> o1  already created;
> 
> o2 := o1.Clone;
> 
> in Clone i want to create new object from TmyObject but in base object in Clone method,like this
> 
> TBaseObject.Clone:TBaseObject;
> begin
>   Result:=TBaseObject(ClassType).Create;//I know it is wrong here
> end;

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;

Type
   TMyObject = class(TBaseObject)
   //   my fields here
   end;

Var
o1, o2:TmyObject;

begin
   o1:=TMyObject.Create;
   o2 := o1.Clone as TmyObject;
end.

Michael.


More information about the fpc-pascal mailing list