Constructor methods v16
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 can 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 can overload a constructor by creating one or more different constructor functions with the same name but with different argument types.
The SPL compiler provides 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 provides a default constructor with the following signature:
The body of the default constructor sets each member to
To create a custom constructor, using the keyword constructor, declare the constructor function in the
CREATE TYPE command, and define the construction function in the
CREATE TYPE BODY command. For example, you might want to create a custom constructor for the
address type that computes the city and state given a
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 example computes the values for
statewhen given a postal code.
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
paymentcan be created with an
NULL, negative, or zero. The default constructor sets
NULL, so you must create a custom constructor whose signature matches the default constructor to prohibit