Constructor (object-oriented Programming) - Eiffel

Eiffel

In Eiffel, the routines which initialize new objects are called creation procedures. They are similar to constructors in some ways and different in others. Creation procedures have the following traits:

  • Creation procedures never have an explicit return type (by definition of procedure).
  • Creation procedures are named. Names are restricted only to valid identifiers.
  • Creation procedures are designated by name as creation procedures in the text of the class.
  • Creation procedures can be directly invoked to re-initialize existing objects.
  • Every effective (i.e., concrete or non-abstract) class must designate at least one creation procedure.
  • Creation procedures must leave the newly initialized object in a state that satisfies the class invariant.

Although object creation involves some subtleties, the creation of an attribute with a typical declaration x: T as expressed in a creation instruction create x.make consists of the following sequence of steps:

  • Create a new direct instance of type T.
  • Execute the creation procedure make to the newly created instance.
  • Attach the newly initialized object to the entity x.

In the first snippet below, class POINT is defined. The procedure make is coded after the keyword feature.

The keyword create introduces a list of procedures which can be used to initialize instances. In this case the list includes default_create, a procedure with an empty implementation inherited from class ANY, and the make procedure coded within the class.

class POINT create default_create, make feature make (a_x_value: REAL; a_y_value: REAL) do x := a_x_value y := a_y_value end x: REAL -- X coordinate y: REAL -- Y coordinate ...

In the second snippet, a class which is a client to POINT has a declarations my_point_1 and my_point_2 of type POINT.

In procedural code, my_point_1 is created as the origin (0.0, 0.0). Because no creation procedure is specified, the procedure default_create inherited from class ANY is used. This line could have been coded create my_point_1.default_create . Only procedures named as creation procedures can be used in an instruction with the create keyword. Next is a creation instruction for my_point_2, providing initial values for the my_point_2's coordinates. The third instruction makes an ordinary instance call to the make procedure to reinitialize the instance attached to my_point_2 with different values.

my_point_1: POINT my_point_2: POINT ... create my_point_1 create my_point_2.make (3.0, 4.0) my_point_2.make (5.0, 8.0) ...

Read more about this topic:  Constructor (object-oriented Programming)