Problem when I store a copy of an object in a new variable

P

pinkfloydfan

Hi all

Having built an object of a user-defined class and stored it an
element of a public array (all works fine), I now wish to copy that
object to a new element and work on the copy.

For example:


Public StoreObjects(100) as NewClass1

Function CreateCopyClass(OldStoreNumber as integer, NewStoreNumber as
integer)
Set StoreObjects(NewStoreNumber)=StoreObjects(OldStoreNumber)
CreateCopyClass=NewStoreNumber
End Function

The problem is that while the object seems to have been copied over to
the NewStoreNumber, when later I look to manipulate that new object
within the code it also changes the data in the original object.

What am I doing wrong please?

Thanks very much for your help
Lloyd
 
G

Guest

when you use the set command, you are setting a reference to the original
object. Then when you perform a change either using the oldstorenumber or
newstorenumber, you are using the same instance of the class.

You need to create a new instance of the class, copy the attributes between
instances. And create a reference to this new instance.
 
P

pinkfloydfan

So, I guess I have to set up the new variable/array element and copy
each property separately to it??

Isn't there any easier way to work with a copy of an object?
 
N

NickHK

You can give your class a .Clone method, so it makes a copy of itself.
You still have to write the code to populate each member of the new instance
with the values in the old instance, but at least then it encapsulated in
the class and any user of you class does not need to know how it is
achieved.
As Tom pointed out, Set will increase the reference count on that object by
1, not create a new object.

NickHK
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top