Constructor Methods v12
A constructor method is a function that creates an instance of an object type, typically by assigning values to the members of the object. An object type may define several constructors to accomplish different tasks. A constructor method is a member function (invoked with a SELF
parameter) whose name matches the name of the type.
For example, if you define a type named address
, each constructor is named address
. You may overload a constructor by creating one or more different constructor functions with the same name, but with different argument types.
The SPL compiler will provide a default constructor for each object type. The default constructor is a member function whose name matches the name of the type and whose argument list matches the type members (in order). For example, given an object type such as:
The SPL compiler will provide a default constructor with the following signature:
The body of the default constructor simply sets each member to NULL
.
To create a custom constructor, declare the constructor function (using the keyword constructor) in the CREATE TYPE
command and define the construction function in the CREATE TYPE BODY
command. For example, you may wish to create a custom constructor for the address
type which computes the city and state given a street_address
and postal_code:
To create an instance of an object type, you invoke one of the constructor methods for that type. For example:
Custom constructor functions are typically used to compute member values when given incomplete information. The preceding example computes the values for city
and state
when given a postal code.
Custom constructor functions are also used to enforce business rules that restrict the state of an object. For example, if you define an object type to represent a payment
, you can use a custom constructor to ensure that no object of type payment
can be created with an amount
that is NULL
, negative, or zero. The default constructor would set payment.amount
to NULL
so you must create a custom constructor (whose signature matches the default constructor) to prohibit NULL
amounts.