[fpc-pascal] Assign() vs AssignTo()
Andreas Schneider
aksdb at gmx.de
Thu Feb 11 16:42:29 CET 2016
Am 2016-02-11 16:13, schrieb Graeme Geldenhuys:
> Hi,
>
> In TPersistent, we have two virtual methods. Assign() which calls
> AssignTo().
>
> 1) Why are they both virtual? It seems like Assign() is what I call a
> template method, farming its work out to other helper methods - in this
> case, AssignTo(). Normally template methods are not virtual, but their
> helper methods (the ones doing the actual work) are. So again, why is
> Assign() virtual?
They are two different directions. AssignTo assigns *from* your current
instance onto another, while Assign assigns *from* the other instance
into yours.
Sure, by default that should be the same, that's why it's sane to have
Assign simply call the other object's AssignTo with Self as target.
But IMHO it can't hurt to have the ability to override that behavior for
only one direction.
> 2) Now seeing that both are virtual, and that is probably not going to
> change in the RTL, which method is the preferred method to override so
> you have the ability to do MyObject.Assign(MySource)? I've been
> overriding Assign(), but thinking that maybe I should have overridden
> AssignTo() instead.
I think that really depends on what direction you want to usually
handle. As far as I understand the code, the call in TPersistent is only
a fallback, intended like that:
if it is not possible to assign some instance onto another instance
(because no class along the hierarchy down to TPersistent implemented an
override for Assign that handles the specific case) it tries, if the
other side maybe can handle it by calling their AssignTo method.
That way you can allow your class to have some
standard/thirdparty/whatever class assigned, while you certainly can't
modify the standard/thirdparty/whatever class to allow assigning *to*
your class (since it doesn't even know your class).
The same goes for the other way around. If you know a foreign class will
try to assign your class, which it doesn't know anything about, it will
ultimately come back calling your AssignTo method which will allow your
class to handle the assignment onto the foreign class.
Best regards,
Andreas
More information about the fpc-pascal
mailing list