Wish Constructor/Destructor on classes

Troberg

Well-Known Member
Licensed User
Longtime User
One thing I miss in B4A is the ability to add constructors and destructors on classes. We have initialize, but it's kind of a halfway solution for constructors.

With full support for these, one could do such things as:

B4X:
Sub Class_Globals
    Dim x As Int
    Dim y As Int
End Sub

Public Sub Initialize(newx As Int, newy As Int)
    x=newx
    y=newy
End Sub

Public Sub Unload()
    Log(X & "," & Y)
End Sub

Then, somewhere else, do stuff like:

B4X:
Dim Position As cPosition(100,200)
Dim Position As cPosition(200,300)
Position=Null

Which, in this simple case would generate this log:

100,200
200,300

In other words, the constructor runs automatically when the object is created (which also means that any arguments in the constructor are enforced by the compiler), and the destructor when it's destroyed, allowing stuff like clean up or saving state.
 

Troberg

Well-Known Member
Licensed User
Longtime User
Ah, I see. I understand the problem.

I disagree that garbage collection makes them unnecessary, though, as there is more one might want to do than cleanup. For example, one might save state, or tell something else "Screw you guys, I'm leaving. Don't try to call me.".

But, garbage collection also makes it harder to do them at the right time. One does not want the destructor called when the object is actually garbage collected, one wants it called when the object becomes ready for garbage collection. Kind of like a "finally" for an object.

Well, well, I'll just add a Finalize() method and remember to call it for the objects in question.
 
Top