[RESOLVED] Copy properties from one class to another
Hi, i've been working with class modules a lot more in a recent program and have come across a problem. It isn't really a problem but there's got to be a better way of doing it. This is what i'm doing:
Code:
'This is in the form module
Private Sub Form_Load()
Dim a As New cTime, b As New cTime
Set a = New cTime
Set b = New cTime
a.Init 35, 20, 4
b = a 'This makes an error "Object doesn't support this property or method"
End Sub
'This is inside class module "cTime"
Private mSeconds, mMinutes, mHours
Public Property Get Seconds()
Seconds = mSeconds
End Property
Public Property Let Seconds(NewV)
mSeconds = NewV
End Property
Public Property Get Minutes()
Minutes = mMinutes
End Property
Public Property Let Minutes(NewV)
mMinutes = NewV
End Property
Public Property Get Hours()
Hours = mHours
End Property
Public Property Let Hours(NewV)
mHours = NewV
End Property
Public Sub Init(Secs, Mins, Hrs)
mSeconds = Secs
mMinutes = Mins
mHours = Hrs
End Sub
So if you run this code you will have an error on the line which says "b = a". That doesn't work (obviously) but now you know what my problem is. How can i copy all of the information from one class module to another? Sure, in this case i could easily do it like this:
Code:
b.Init a.Seconds, a.Minutes, a.Hours
but that becomes very impractical when you have 10+ properties.
Re: Copy properties from one class to another
The usual way to do it is roughly on the same lines as you have already thought of, but with a small and significant difference - you provide a method in the class itself (usually called .Clone) to do all the work of creating a copy, eg:
Code:
Public Function Clone as cTime
'Return a copy of this instance
'Create a blank copy
Set Clone = New cTime
'Set properties as apt
With Clone
.Seconds = mSeconds
.Minutes = mMinutes
...
End With
End Function
The usage would then be like this:
Code:
Private Sub Form_Load()
Dim a As New cTime
Set a = New cTime
a.Init 35, 20, 4
Dim b As cTime '(no New!)
Set b = a.Clone
End Sub
Re: Copy properties from one class to another
Quote:
The usual way to do it is roughly on the same lines as you have already thought of, but with a small and significant difference - you provide a method in the class itself (usually called .Clone) to do all the work of creating a copy, eg:
Thanks, that seems to be a pretty good method, it's essentially the same as what i knew how to do except you only do it once in the class module!