Sign in Join

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

Mailing lists / fpc-pascal / 2003-02

Classes and copying

4 messages · 4 people ·

Reply by email Subscribe to this list Your subscription

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

James Mills

Hi all,

With respect to classes (and perhaps also objects), how do you copy the contents of a class in memory (an object) to another?

ie:

var
	a: TClass;
   b: TClass;
begin
  a := TClass.init;
  b := a; //This only copies the pointer and doesn't work ??
end.

cheers
James

Michael Van Canneyt
to James Mills
James Mills wrote 16 lines
Hi all, With respect to classes (and perhaps also objects), how do you copy the contents of a class in memory (an object) to another? ie: var a: TClass; b: TClass; begin a := TClass.init; b := a; //This only copies the pointer and doesn't work ?? end.

This indeed only copies the pointer. if you want to do more than that, then you need to implement this yourself.

TPersistent implements the 'Assign' method for this. You can create a descendent from TPersistent, override the Assign method, and then copy fields as necessary in the new Assign method.

Michael.

Matt D. Emson
Show quoted text 6 lines
This indeed only copies the pointer. if you want to do more than that, then you need to implement this yourself. TPersistent implements the 'Assign' method for this. You can create a descendent from TPersistent, override the Assign method, and then copy fields as necessary in the new Assign method.

And also that, whilst this sounds tedious, you could (in Delphi mode only I guess) use RTTI to automate some of it. There is at least one component (have a look for zproplst.zip on Torry.net, or if you have the Delphi source there is a hidden TPropList class) that goes through the published members and gets all their names and types. You can then use the routines in the unit Typinfo (might be part of fcl I guess, should be in the Delphi compatible part of the RTL at least though) to retrieve and set their values. Caveat, you *must* declare all members that you with to get at as being Published, it only really works well for properties and your classes should descend from Tpersistent.

Having said all that, it works really well in Delphi, and I assume Delphi mode (S2 or Sd). Does the TP or the ObjFPC mode support RTTI and the Typinfo unit?

Noting also that whilst C++ has a nice syntax for this (the 'copy' constructor/operator overloading dodge) all it really does is the same as Assign (mostly) but just in a more convoluted way.

Matt

Sebastian Günther
to Matt D. Emson
Having said all that, it works really well in Delphi, and I assume Delphi mode (S2 or Sd). Does the TP or the ObjFPC mode support RTTI and the Typinfo unit?

Yes, what you have described should work well in FPC, too.

- Sebastian