[fpc-pascal] Quick Modern Object Pascal Introduction, for Programmers
michalis.kambi at gmail.com
Tue Jun 21 13:08:43 CEST 2016
2016-06-21 12:14 GMT+02:00 Marco van de Voort <marcov at stack.nl>:
> In our previous episode, Michalis Kamburelis said:
>> - A section about TPersistent.Assign. This is the "basic approach to
>> cloning" that should probably be shown first. See it here:
> See also
> That is for an own root class and pre class helpers, but you could do it also in or TPersistent
> type tpersisthelp = class helper for TPersistent
> function Clone(t: TPersistentClass = nil): TPersistent;
> function tpersisthelp.Clone(t: TPersistentClass = nil): TPersistent;
> if Assigned(t) then
> Result := t.Create
> Result := TPersistentClass(Self.ClassType).Create;
> Since TComponent declares a virtual destructor that might even be better.
I saw your post on stackoverflow before writing my article:)
But doing this on TPersistent means that you avoid calling the
constructor of the actual class. If you use this helper on a class
TMyClass, you will have an instance of TMyClass that "bypassed" the
constructor of TMyClass. Only "TPersistent.Create" was called. I
suspect that in real-world usage, a lot of classes will fail to work
correctly then, since code inside TMyClass often assumes that TMyClass
constructor was performed. I know that a lot of my own classes will
fail because of this...
That's why I would limit this usage only to the cases when you have a
virtual constructor on the base class. Only then the final class has a
chance to execute it's proper constructor.
-------------- next part --------------
A non-text attachment was scrubbed...
Size: 1063 bytes
Desc: not available
More information about the fpc-pascal