Jump to content
  • Advertisement


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


[Visual Basic] Copy objects

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

If you intended to correct an error in the post then please contact us.

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 this post

Link to post
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.


Public A As Integer
Public B As Integer

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


Dim x As SampleClass
Dim y As SampleClass
Set x = New SampleClass
x.A = 1
x.B = 1
Set y = x.Copy
y.A = 2
MsgBox x.A
MsgBox y.A

Share this post

Link to post
Share on other sites
Implement a Clone() member function:

'' BEGIN MyClass.cls
Public x as Integer
Public y as Integer
Public z as Integer

Public Function Clone() as MyClass
Dim newObj as New MyClass
newObj.x = x
newObj.y = y
newObj.z = z
Set Clone = newObj
End Function

'' END MyClass.cls

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!