I need to make some custom objects in VBA that will need to reference each other and I have a some issues.
First - how do object constructors work in VBA? Are there constructors?
Second - are there destructors? How does VBA handle the end of the object lifecycle? If I have an object that references others (and this is their only reference), then can I set it to Nothing and be done with it or could that produce memory leaks?
This quasi-OO stuff is just a little bit irritating.
Mar 21, 2021 • 2 min read. If you are familiar with other object-oriented programming languages, you are likely familiar with the concept of constructors: In class-based object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object.
Constructors and DestructorsA destructor is a special member Sub of a class that is executed whenever an object of its class goes out of scope. A destructor has the name Finalize and it can neither return a value nor can it take any parameters.
The Initialize event occurs when you: Create a new instance of a class directly by using the New keyword with the Set statement. Dimension an object variable using the New keyword and creating an instance of a class indirectly by setting or returning a property or applying a method defined in the class module.
The main difference between classes and modules is that classes can be instantiated as objects while standard modules cannot.
VBA supports Class Modules. They have a Class_Initialize event that is the constructor and a Class_Terminate that is the destructor. You can define properties and methods. I believe VBA uses reference counting for object lifecycle. Which is why you see a lot of Set whatever = Nothing in that type of code. In your example case I think it will not leak any memory. But you need to be careful of circular references.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With