DOODC84 DOODC84 - 4 months ago 24x Question

Visual Basic - stack overflow from object references

I'm making a little text based adventure game in VB and I have different classes for different functions in the game (to keep organized). Well, I need two classes to reference each other. I'll explain.

So these two classes are

. I created references in the files so that they could execute methods in each other's code.

like so:

Dim comm As New Commands

And then
in the same way.

Dim dir As New Direct

But when I run the program to see if it works, it throws a
. I think these classes are doing an infinite loop of references.

Is there a way I can fix this?


You can reference one class from the other, but you can't have them both create a new instance of the other.

In your current case, say you create one Commands, this creates one Direct, this creates one Commands, this creates one Direct, etc., etc. This will fill the heap and the stack, but the stack runs out first with constructor functions.

The solution is to use a reference only, so omit the New keyword from at least one of these classes. Without knowing the specifics, it's not really possible to give more specific advise. Typically, though, this kind of construction would work:

Public Class Commands
   Private dir As Direct

   Public Sub New()
       dir = New Direct(Me)
   End Sub
End Class

Public Class Direct
    Private cmd As Commands

    Public Sub New(ByVal cmdInstance As Commands)
        cmd = cmdInstance
    End Sub
End Class