#### Archived

This topic is now archived and is closed to further replies.

# [Visual Basic] Copy objects

This topic is 5651 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I''m a bit confused with VB''s references. I''m in need of copying an object, and as I figure, VB will only work with references, and I''m unable to find a way to give my classes a copy constructor . To illustrate, say I have a class T, with a "property" a, and I do like this
Dim x As New T
Dim y As New T

x.a = "1"
Set y = x     // Obviously wrong
y.a = "2"

Now, both x.a and y.a equals "2". No wonder, as they both are referencing the same object. My question is how do I copy objects in a similar manner. I would like to avoid having to instantiate the new object and manually copy each member, as this particular object contains other objects that conatin other object (and so forth).

##### Share on other sites
As far as I know, the only way to do it is to write your own Copy function that creates a new instance of the class and sets the values as you want them.

SampleClass:

  Public A As IntegerPublic B As IntegerPublic Function Copy() As SampleClass    Dim newobject As New SampleClass    newobject.A = Me.A    newobject.B = Me.B    Set Copy = newobjectEnd Function

Usage:

  Dim x As SampleClassDim y As SampleClassSet x = New SampleClassx.A = 1x.B = 1Set y = x.Copyy.A = 2MsgBox x.AMsgBox y.A

##### Share on other sites
Ok, so I feared. I''ll try that. Thanks

##### Share on other sites
Implement a Clone() member function:

  '' BEGIN MyClass.clsPublic x as IntegerPublic y as IntegerPublic z as IntegerPublic Function Clone() as MyClass  Dim newObj as New MyClass  newObj.x = x  newObj.y = y  newObj.z = z  Set Clone = newObjEnd Function'' END MyClass.cls

1. 1
2. 2
3. 3
Rutin
22
4. 4
frob
17
5. 5

• 33
• 13
• 12
• 10
• 12
• ### Forum Statistics

• Total Topics
632573
• Total Posts
3007144

×