Cloning objects

Unlike records, objects in Delphi are reference types. When you create an object, memory is dynamically allocated and stored in the object variable. A variable that stores an object is actually just a pointer, pointing to the memory where the real object is stored.

The following code fragment therefore doesn't create a copy of an object:

var  a, b: TSomeObject; begin  a := TSomeObject.Create;  b := a;  // a and b are now sharing the same object  // they are both pointing to the same memory addressend;

To create a clone of an object, we have to create a new object and copy the content of the object from the original to the new object. There are three idiomatic ways to do that in Delphi and all are demonstrated in the prototype project. ...

Get Hands-On Design Patterns with Delphi now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.