A special class method called when an object instance of a class is destroyed. With some languages they are called when the object instance goes out of scope, with some languages you specifically have to call the destructor in code to destroy the object, and others use a garbage collector to dispose of object instances at specific times.
Desctructors are commonly used to free the object instance but with languages that have a garbage collector object instances are disposed of when appropriate. Either way, destructors or their equivalent are commonly used to free up resources allocated in the class constructor.
Languages Focus: Destructor
Are object instances freed with a garbage collector? Or, do you have to destroy object instances.
ASP Classic Destructor
When an object instance is destroyed, ASP calls a special parameter-less sub named Class_Terminate. For example, when the variable falls out of scope. Since you cannot specify parameters for this sub, you also cannot overload it.
To explicitly destroy an object, use Set YourClass = nothing. If the Class object is explicitly destroyed, the client returns with the script engine error details.
When an object instance is created from a class, ASP calls a special sub called Class_Initialize.
Working Example
The following working example contains both a constructor and destructor, ASP's Class_Initialize and Class_Terminate subs. In this example, we are explicitly destroying the object by using Set MyRobot = Nothing. In ASP Classic, it is recommended that you explicitly destroy all objects.
<%@LANGUAGE=VBScript%>
<%Option Explicit%>
<html>
<body>
<%
Dim MyRobot
Set MyRobot = new Cyborg
Response.Write "<br>My robot's name is " & MyRobot.CyborgName & "."
//Explicitly destroy object.
Set MyRobot = Nothing
%>
</body>
</html>
<%
Class Cyborg
Public CyborgName
Public Sub Class_Initialize
Response.Write "<br>Class created"
CyborgName = "Cameron"
End Sub
Public Sub Class_Terminate
Response.Write "<br>Class destroyed"
End Sub
End Class
%>
The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.