Matt Dillard
Matt Dillard

Reputation: 14853

When is this VB6 member variable destroyed?

Suppose I have a class module clsMyClass with an object as a member variable. Listed below are two complete implementations of this very simple class.

Implementation 1:

Dim oObj As New clsObject

Implementation 2:

Dim oObj As clsObject

Private Sub Class_Initialize()
    Set oObj = New clsObject
End Sub

Private Sub Class_Terminate()
    Set oObj = Nothing
End Sub

Is there any functional difference between these two? In particular, is the lifetime of oObj the same?

Upvotes: 8

Views: 374

Answers (3)

Darrel Miller
Darrel Miller

Reputation: 142084

In implementation 1 the clsObject will not get instantiated until it is used. If it is never used, then the clsObject.Class_Initialize event will never fire.

In implementation 2, the clsObject instance will be created at the same time that the clsMyClass is instantiated. The clsObject.Class_Initialize will always be executed if clsMyClass is created.

Upvotes: 5

Rick
Rick

Reputation: 610

The object variable will be destroyed whenever garbage collection determines there are no more references to said object. So in your two examples, assuming the scope of clsObject is the same, there is no difference in when your object will be destroyed.

Upvotes: 0

Mitchel Sellers
Mitchel Sellers

Reputation: 63126

If in implementation 1 the declaration is inside the class and not a sub, yes the scope is the same for both examples.

Upvotes: 0

Related Questions