User-Defined Constructors and the Use of static opCall()

User-defined constructors

You have already learned about the behavior of the compiler-generated constructor. Since that constructor is suitable for most cases, there is no need to define a constructor by hand.

Still, there are cases where constructing an object involves more complicated operations than assigning values to each member in order. Let’s consider this example:

struct Duration {
    int minute; 
}

The compiler-generated constructor is sufficient for this single-member struct:

time.decrement(Duration(12));

Since that constructor takes the duration in minutes, the programmers would sometimes need to make calculations:

// 23 hours and 18 minutes earlier
time.decrement(Duration(23 * 60 + 18));

// 22 hours and 20 minutes later
time.increment(Duration(22 * 60 + 20));

To eliminate the need for these calculations, we can design a Duration constructor that takes two parameters and makes the calculation automatically:

struct Duration {
    int minute;
    this(int hour, int minute) { 
        this.minute = hour * 60 + minute;
    }
}

Since hour and minute are now separate parameters, the users simply provide their values without needing to make the calculation themselves:

// 23 hours and 18 minutes earlier
time.decrement(Duration(23, 18));

// 22 hours and 20 minutes later
time.increment(Duration(22, 20));

First assignment to a member is construction

When setting values of members in a constructor, the first assignment to each member is treated specially: Instead of assigning a new value over the .init value of that member, the first assignment actually constructs that member. Further assignments to that member are treated regularly as assignment operations.

This special behavior is necessary so that immutable and const members can be constructed with values known only at run time. Otherwise, they could never be set to the desired values as assignment is disallowed for immutable and const variables.

The following program demonstrates how the assignment operation is allowed only once for an immutable member:

Get hands-on with 1000+ tech skills courses.