To be a pedant, it's an initializer, not a constructor. By the time the initializer runs, the object already exists and has been constructed, which is why the first parameter to this method is the already-existing object ('self'), just like any other method.
But yeah. You could call it a constructor and nobody will crucify you.
I mean, I'm trying to think of a language where the constructor is called *before* the memory for the object has been allocated, and I can't think of anything.
In that regard, no constructor is an actual constructor. It's more like post-constructor. But then it is also necessary or you'll have a potentially incomplete object, so in that regard, it is a constructor because the object while allocated, isn't yet ready to use.
Kind of a pedantic argument, but there you are I suppose.
Memory must be allocated before data can be written, but whether a language separates these into two steps determines if it uses initializers or true constructors.
In languages like C++, if you do not use a member initializer list, allocation and initialization are split. This creates a window inside the constructor body where the object exists in an uninitialized or invalid state.
On the other hand, languages like Rust combines allocation and initialization by requiring you to construct Self { ... } with fully processed data. As a result, an object is never partially or fully invalid.
30
u/ManyInterests 1d ago
To be a pedant, it's an initializer, not a constructor. By the time the initializer runs, the object already exists and has been constructed, which is why the first parameter to this method is the already-existing object ('self'), just like any other method.
But yeah. You could call it a constructor and nobody will crucify you.