[fpc-pascal] Cloning objects?

Andreas Schneider aksdb at gmx.de
Thu Mar 20 07:53:14 CET 2014


On 19.03.2014 23:01, Timothy Groves wrote:
> Is there a drop-dead simple way to clone an object?
>
> I've got a small tree of classes (tBaseProfile, and four descendants
> of such).  Only the descendant classes are instantiated.  I need to be
> able to create new copies of these objects for use in other lists.
>
> At the moment, I am writing a Duplicate method that returns the new
> object.  But this means assigning all of the data to the duplicated
> object.  There must be an easier way!
There is usually a good reason to NOT do it blindly for all members and
why you don't find a default "clone" method in any programming language
in can think of right now.

Just think about it: you clone a database object (from an ORM or
similar). How far does the clone/copy go? Will you also clone the
associated database connection object? Probably not, so your manual code
would only assign the same reference to the clone. However the table
name, field name, sql statement etc. will be copied.

Or think about file access: your object has a TFileStream as member.
Will you clone that? What if the access was read/write and maybe even
exclusive?

IMHO there is no one-size-fits-all here.

Best regards,
Andreas

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 293 bytes
Desc: OpenPGP digital signature
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20140320/0e7e11ea/attachment.sig>


More information about the fpc-pascal mailing list