Class Constructors

next up previous contents index
Next: Instance Variable Selection Up: Expressions Previous: Constructors

Class Constructors

Within a class (10.4) and its module (10.1), new objects belonging to the class can be created and initialized using a special constructor for the class. This constructor is similar to the one for "record"s and "struct"s, and also to the specialized constructor in the "make" statement (8.17). It has the form:
<type_designator> "{" [<ivar_inits>] "}"
The type_designator must name a class type (10.4)); this gives the type of the constructed object. All class constructor expressions have a (possibly empty) ivar_inits section surrounded by curly braces. This section consists of two parts:
        <ivar_inits> -> <field_inits> ";" <maker_invoc> | <field_inits> | <maker_invoc>
        <field_inits> -> <field_init> ["," <field_init>]*
        <field_init> -> <idn> ":=" <expr>
        <maker_invoc> -> <idn> [<actual_parms>] "(" [<args>] ")"
        <actual_parms> -> "[" <type_list> "]"
        <type_list> -> <type_designator> ["," <type_designator>]*
The field_inits part initializes the instance variables of the class; there must be one field_init for each instance variable. (If the class has no instance variables, field_inits is not used.) The maker_invoc part is used to initialize inherited instance variables. This invocation is present iff the class named by the type_designator has a superclass (10.5.3); [tex2html_wrap2910] must name a maker (10.5.2) provided by (10.5.1) the superclass.

The constructor creates a new object of the class type, evaluates the field_init expressions (in an arbitrary order), assigns the results to the associated instance variables of the new object, and calls the superclass maker if the maker_invoc part is present. If all of these steps terminate normally (i.e., they do not raise an exception), the class construction expression terminates normally with the newly-created object as the result.

For example if a class "C" has two instance variables, "x" of type "int" and "y" of type "char", and does not have a superclass, then

        n: C := C {x := 3, y := 'A'}
creates a new "C" object with the indicated values in its instance variables and assigns it to n.