Nice TWiki > Dev > CurrentDiscussions > NiceConstructors > CustomConstructors (r1.1) TWiki webs:
Dev | Doc | Main | TWiki | Sandbox
Dev . { Changes | Index | Search | Go }
Construction is the process of creating a new object whose fields have some meaningful value. Currently, only the automaticly generated default constructor does that. It takes the value of each field as a named parameter.

Basically, a custom constructor could be defined as a normal method:

class Point { double x; double y; }
Point createPoint(double angle, double distance) = new Point(x: ..., y: ...);

The problem with this solution is that a subclass can not make use of the custom constructor for its parent, since it includes the creation of the object itself, instance of the parent class. Instead, we want the a custom constructors takes the new instance (this), and sets its fields. However, this cannot be done with a normal method, since we do not want to give a way to create an uninitialized instance, as this would be unsafe (like accessing this in a Java constructor is unsafe).

Therefore, we propose to add the concept of a custom constructor. Its declaration is similar to a method default implementation, except that it has no return type, and its name is the class C being constructed. The parameter list is arbitrary, as is the body, except the last instruction: it must be a call of the form new C(...), targetting either the automatic constructor, or another custom constructor. This guarantees that all fields are set to a correct value. The body before this last instruction can be used to compute the arguments of this last call. Nowhere is this accessible.

class Point { double x; double y; }
Point(double angle, double distance) { new Point(x: ..., y: ...); }

This allows to create a new point with new Point(angle: ..., distance: ...). Furthermore, a subclass can be constructed by reusing this custom constructor:

class ColoredPoint extends Point { String color; }

var ColoredPoint redOrigin = new ColoredPoint(angle: 0, distance: 0, color: "red");

A custom constructor can also reuse the parent custom constructor indirectly, through the default constructor of the child class:

ColoredPoint(double angle, double distance, int color) { new ColoredPoint(angle: angle, distance: distance, color: ...); }

-- DanielBonniot - 01 Oct 2003

Topic CustomConstructors . { Edit | Attach | Ref-By | Printable | Diffs | r1.27 | > | r1.26 | > | r1.25 | More }
Revision r1.1 - 01 Oct 2003 - 21:00 GMT - DanielBonniot
Parents: WebHome > CurrentDiscussions > NiceConstructors
Copyright © 1999-2003 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback.

Dev.CustomConstructors moved from Dev.NonDefaultConstructors on 01 Oct 2003 - 21:08 by DanielBonniot - put it back