5.3.1.10 Lifecycle Handler Declarations

 lifecycle-handler-name = “Class_Initialize” / “Class_Terminate” 

Static Semantics

  • A lifecycle handler declaration is a subroutine declaration that meets all of the following criteria:

    • It is contained within a class module.

    • It’s procedure name is a <lifecycle-handler-name>

    • The <procedure-parameters> element of the <subroutine-declaration> is either not present or does not contain a <parameter-list> element

 

Runtime Semantics

§ If a class defines a Class_Initialize lifecycle handler, that subroutine will be invoked as an method each time an instance of that class is created by the New operator, by referencing a variable that was declared with an <as-auto-object> and whose current value is Nothing, or by call the CreateObject function (section 6.1.2.8.1.4) of the VBA Standard Library. The target object of the invocation is the newly created object. The invocation occurs before a reference to the newly created object is returned from the operations that creates it.

§ If a class defines a Class_Terminate lifecycle handler, that subroutine will be invoked as an method each time an instance of that class is about to be destroyed. The target object of the invocation is the object that is about to be destroyed. The invocation of a Class_Terminate lifecycle handler for an object can occur at precisely at the point the object becomes provably inaccessible to VBA program code but can occur at some latter point during execution of the program

§ In some circumstances, a Class_Terminate lifecycle handler can cause the object to cease to be provably inaccessible. In such circumstances, the object is not destroyed and is no longer a candidate for destruction. However, if such an object later again becomes provably inaccessible it can be destroyed but the Class_Terminate lifecycle handler will not be invoked again for that target object. In other words, a “Class_Terminate” lifecycle handler executes at most once during the lifetime of an object.

§ If the error-handling policy of a Class_Terminate lifecycle handler is to use the error-handling policy of the procedure that invoked it, the effect is as if the Class_Terminate lifecycle handler was using the default error-handling policy. This means that errors raised in a Class_Terminate lifecycle handler can only be handled in the handler itself.