Constructor: Introduction

Let’s talk about constructors and their syntax.

Chapter overview

Although this chapter focuses only on structs, most of the topics that are covered here apply to classes as well.

Four member functions of structs are special because they define the fundamental operations of that type:

  • Constructor: this()

  • Destructor: ~this()

  • Postblit/Copy Constructor: this(this)

  • Assignment operator: opAssign()

Although these fundamental operations are handled automatically for structs and need not be defined by the programmer, they can be overridden to make struct behave in special ways.

Constructor

The responsibility of the constructor is to prepare an object for use by assigning the appropriate values to its members.

You have already seen examples of constructors in the previous chapters. When the name of a type is used as a function, it is actually the constructor that gets called. You can see this on the right-hand side of the following line:

auto busArrival = TimeOfDay(8, 30);

Similarly, a class object is being constructed on the right-hand side of the following line:

auto variable = new SomeClass();

The arguments that are specified within parentheses correspond to the constructor parameters. For example, the values 8 and 30 above are passed to the TimeOfDay constructor as its parameters.

In addition to the different object construction syntaxes that we have mentioned so far; const, immutable, and shared objects can be constructed with the type constructor syntax as well (e.g., as immutable(S)(2)).

For example, although all three variables below are immutable, the construction of variable a is semantically different from the constructions of variables b and c:

Get hands-on with 1400+ tech skills courses.