Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2014-03

Cloning objects?

5 messages · 5 people · –

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Timothy Groves

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!

silvioprog
to Timothy Groves

2014-03-19 19:01 GMT-03:00 Timothy Groves :

Show quoted text 9 lines
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!

I'm working on something right now (using RTTI). I need to clone any object, even third party objects. I use an OPF and a HTTP framework and both work directly with objects, and now came the need to clone objects ( http://goo.gl/VVTFcu).

I'll post the code here soon ...

Silvio Clécio My public projects - github.com/silvioprog
Andreas Schneider
to Timothy Groves: Is there a drop-dead simple way to clone an object? I've got a small tree of classes…
Timothy Groves wrote 9 lines
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