Class Constructors


The most recent version of the point class used a constructor set to initialize the point.

A constructor is a method that is used to initialize an object when it is created. The name of a constructor method matches the name of the class and the constructor method has no return type. Thus, the general form of a constructor is as follows.

class-name(parameter-list)
{
 ...
}

Usually, a constructor is used to give values to fields of the class or to perform any other startup required to create a fully formed object.

The version of the point class shown below provides two constructors used to initialize the point.

// point_e - returning a value

class my_point
{
    x
    y

    my_point() {}

    my_point(x_set y_set)
    {
        x = x_set
        y = y_set 
    }

    write()
    {
        s = "point = (" + x.to_string() + "," + y.to_string() + ")"
        s.println()
    }

    length()
    {
        norm = x * x + y * y
        return norm.square_root()
    }
      
}

point_e()
{
    p = new my_point(3.0 4.0)
    p.write()
    l = p.length()
    s = "length == " + l.to_string()
    s.println()
}

Allocation and initialization are achieved though the following single call.

p = new my_point(3.0 4.0)

The call to the new operator now calls the constructor for the class point. The arguments 3 and 4 are substituted for the parameters x_set and y_set (respectively) of the appropriate constructor. The allocated object that is returned from this call is fully initialized and then assigned to reference p. The output of the program is shown below.

point = (3,4)
length == 5

The New Operator

Once class constructors have been covered, it is time to reconsider the new operator. The general form of the new operator as it applies to classes is as follows.

class-variable = new class-name()

or

class-variable = new class-name(parameter-list)

Here, class-variable is a variable of the class being created. The class-name is the name of the class being instantiated. The class name followed by parentheses (first case) specifies the default constructor for the class. The class name followed by a parenthesised parameter list specifies a non-default constructor of the class.

Given that virtual memory is finite, it is possible that the new operator will be unable to allocate memory for an object. When this happens, an exception will be thrown. Exceptions will be covered in a later chapter.