What are Constructors and Destructors?

There are two special class methods which you may optionally add to a class.  They meet a very specific need: automatic initialization when an object is created, and cleanup when an object is destroyed.  Technically, they are known as constructor and destructor methods, and can perform almost any functionality needed by your object: initialization of variables, reading/writing data to/from disk, etc.  You do not call these methods directly from your code.  If they are present in your class, PowerBASIC automatically calls them each time an object of that class is created or destroyed.  If you choose to use them, these special class methods must be named CREATE and DESTROY.  They may take no parameters, and may not return a result.  They are defined at the class level, so they may never appear within an INTERFACE definition.

CLASS MyClass
  INSTANCE MyVar AS LONG

  CLASS METHOD CREATE()
    ' Do initialization
  END METHOD

  CLASS METHOD Destroy()
    ' Do cleanup
  END METHOD

  INTERFACE MyInterface
    INHERIT IUNKNOWN
    METHOD MyMethod()
      ' Do things
    END METHOD
  END INTERFACE
END CLASS

As displayed above, CREATE and DESTROY must be placed at the class level, before any INTERFACE definitions.  You should note that it's not possible to name any standard method (one that's accessible through an interface) as CREATE or DESTROY.  That's just to help you remember the rules for a constructor or destructor.  However, you may use these names as needed to describe a method external to your program.

A very important caution:  You must never create an object of the current class in a CREATE method.  To do so will cause CREATE to be executed again and again until all available memory is consumed. This is a fatal error, from which recovery is impossible.

 

See Also

What is an object, anyway?

Just what is COM?

What is a Class Method?

What is DISPATCH?