# constructors

Definition: | class identifier function identifier(class this,[args]) -- constructor procedure ~identifier(class this) -- destructor end class
Description: | Classes can also have explicit constructors and/or destructors. There is an automatic this parameter on both constructors and destructors, which should not be explicitly declared, and is only documented in case for some reason (like builtins\structs.e does) you are invoking these routines via call_func/call_proc(). The parameters on the constructor (if any) must be matched by the new() call. The destructor takes no parameters, other than the implicit this described above.
pwa/p2js: | Not supported.
Example: |
    class five nullable
        public integer n = 3
        function five(integer n = 4)
            printf(1,"constructor five(%d) called\n",n)
            this.n = n
            return this
        end function
        procedure ˜five()
            printf(1,"destructor ˜five(%d) called\n",n)
        end procedure
    end class
    five v = new({5})
    if v.n!=5 then ?9/0 end if
    v=NULL
    -- output:
    -- constructor five(5) called
    -- destructor ˜five(5) called
Note: should you copy/paste the above code, you may need to replace the (unicode) tilde ('˜') with the ascii one ('~'). (As per wikipedia, much malarkey exists regarding 0xA1AD, U+223C, U+301C, U+FF5E, 0xA2A6, U+02DC, 0x8160, and the one we want, U+007E, to list just a few!) If no constructor method is defined, the elements of the parameter of new() are assigned in order to the internal fields of the class, otherwise they are assigned in order to the constructor parameters. On entry the implicit this parameter is a fully-formed instance though technically there is nothing to prevent you from completely replacing it, which you might do, for example, in a singleton class. Of course you could instead just write a more traditional new_five() function, as in one outside of any class that invokes new() and returns the result from that, possibly tweaked a little. Also note that destructors such as that ~five() are not necessarily invoked in a timely fashion, or indeed even guaranteed to be called at all, in particular if the program crashes or aborts suddenly. You should not overly rely on destructor calls: freeing resources or even estimating time to completion should be fine, but it would probably be nothing short of utter madness and sheer frustration to use a destructor, for instance, to print the subtotals on a report. Certainly the comparatively innocent act of saving the initial state in some "dbg" variable would most likely whack everything out-of-order, plus it is clearly better to say "do it now" than moan that "whenever" isn’t quite happening at the expected time.
Implementation: | As per struct
See Also: | class