Copying Object Variables and Values 

Since an object variable is a pointer to a value, the following simple assignment statement does not copy the value of an object, it copies an object pointer:

My_loc = Another_loc

At the conclusion of this instruction, My_loc and Another_loc both point to the same object value.  Furthermore, if My_loc was the only pointer to a different object value, that object value will have been deleted (“deallocated”).

This use of pointers allows some sophisticated programming techniques, but it can also be confusing.  For example, after the assignment statement above, changing a property of either My_loc or Another_loc will alter the property as seen by the other object. For example:

Dim My_Loc1 As New Location   ' Create new location value
Dim My_Loc2 As Location ' Does not create value
Dim tmp As Double
My_Loc1.X = 10
My_Loc2 = My_Loc1 ' Both Loc2 and Loc1 now ' have the same value pointer
tmp = My_Loc2.X ' tmp gets the value 10
My_Loc1.X = 20
tmp = My_Loc2.X ' tmp now gets the value 20

Clone Method

Many classes include a Clone method to create an exact copy of an object.  The value of the Clone method is a new object value that is the same as the referenced object.  When this value is assigned to a variable, it is independent of the original object value.

For example:

Dim My_Loc1 As New Location   ' Create new location value
D im My_Loc2 As Location ' Does not create value
Dim tmp As Double

My_Loc1.X = 10
My_Loc2 = My_Loc1.Clone ' Loc2 gets a copy of Loc1
tmp = My_Loc2.X ' tmp gets the value 10
My_Loc1.X = 20
tmp = My_Loc2.X ' tmp still gets the value 10

Nothing

The keyword Nothing is a built-in function that returns an object with no value.  If you assign Nothing to an object variable, its previous pointer is removed and any attempt to access the variable results in an error.  When an object variable is newly declared its value is Nothing unless a New clause was specified.

Assigning Nothing to an object variable releases the memory associated with the object value, provided it is not being used elsewhere.