[fpc-pascal] Clone a instance of object

Sven Barth pascaldragon at googlemail.com
Mon Sep 23 07:50:41 CEST 2013


Am 23.09.2013 07:15 schrieb "Zaher Dirkey" <parmaja at gmail.com>:
>
> 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;
>
> A
> ny good idea?

You need to add a "Result.Assign(Self)" to your clone call and implement a
virtually inherited "Assign" method in each class where you copy all
fields. This is how "TPersistent" and its descendants do it as well.

Regards,
Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20130923/fec46647/attachment.html>


More information about the fpc-pascal mailing list