Could someone explain the difference between:
(1.)
newObj := TMyObject.Create;
newObj.Assign(oldObj);
and
(2.)
newObj := oldObj;
in 2. does newObj and oldObj refer to the same single object?
Sorry if this has been covered before but is is difficult to search :=
Assuming that
Assignis implemented correctly, thisTMyObject(viaCreate)newObj(via the:=operator)oldObj, makingnewObja functionally exact copy ofoldObj(viaAssign).The end result here is that you have two completely separate instances of
TMyObjectwhich are, at this point, exact copies of each other.The above simply copies a reference to
oldObjand stores it in the variablenewObj. In this case you still only have one instance ofTMyObjectand both variablesnewObjandoldObjpoint to the same instance. If you modify the state of that object using either variable, both will reflect those changes since they both point to the same underlying object.This is in contrast to the example above where you have two separate object whose state can diverge as both objects are modified independently.
Conceptually, variables of objects (classes) are generally referred to as "reference types". Variables of this type are essentially just pointers (if this is more familiar). Assignment (
:=) with reference types only copies the reference to the object, not the object itself.The only material exception to this are
stringtypes, which have many properties of reference types, but are managed by the compiler to also behave in many ways as value types (modifying a string produces a new modified copy rather than modifying the original string which may be referenced elsewhere).See also : To copy from one object to another, can I assign the variables directly, or must I assign their properties individually?