logoalt Hacker News

ninkendo • today at 3:53 PM • 12 replies • view on HN

Constructors are such an odd duck to me. On the one hand, you have languages like C++ and Swift which have construction as a first-class concept, with tons of rules you need to memorize (Swift's "convenience" vs "designated" initializers are a real treat to unpack).

Then you have languages like Rust, Go, Zig, etc which don't have them at all, constructors are just static functions in the namespace of the type, which return an instance of that type.

For the life of me I've never understood why you'd want the former. I'm sure there's a reason, but I never miss it when using languages in the latter category.

The explanation you typically hear is about OO and inheritance, but I don't buy it: If Animal had a ::new() that initialized private state, Cow could have a ::new() too that could call Animal::new() if it wanted, then do further initialization, etc... I don't think there's anything about inheritance that says constructors are a must. (Edit: In fact, ObjC does exactly this. I should have remembered that given that I did ObjC for a living for a while.)


Replies

Calavar • today at 4:11 PM

For ergonomics in the general case, I agree that it's not even a question, the Rust/Zig create-and-return approach wins on every count.

However, create-and-return makes in place construction difficult. C++ allows you to construct directly into any pinned memory block with satisfactory size and alignment, whereas create-and-return requires you to construct elsewhere and then copy the bytes. This has downstream implications:

- The address of "this" always changes at least once, which makes self-referential data structures and cyclic data structures more difficult. Now you have a pointer fixup step, or you are passing around some form of handle rather than raw pointers. These solutions can range from trivial to complicated, fast to slow, depending on the specific patterns in your code base. A simpler work around is to always construct with a fresh heap allocation and return a pointer to it, which, again, may or may not be an acceptably performant solution for your particular problem.

- You have to rely on your optimizer to do copy elision, which is not a guarantee. Not an issue for small objects, but it can become an issue for larger ones or for many repeated constructions.

➕ show 3 replies
layer8 • today at 6:13 PM

The main idea is that the class in question establishes the invariants of the new instance through the constructor. Subclasses have no business to fudge anything about the invariants of the superclass, or to see the uninitialized state of the superclass instance (and possibly expose it to client code in that invalid state), and also must not be able to see an uninitialized superclass instance; same as any other client code. So an invocation order has to be enforced such that the superclass constructor is always called before the subclass constructor is executed with access to the superclass instance.

The whole idea of OOP, aside from inheritance, is that the class implementation controls and ensures the invariants of its instances, protecting their internal state from client code. This limits code that might accidentally set the object to an incorrect state to the class implementation. If the class implementation is correct, then the object can’t possibly get into an invalid state, because only the class implementation can manipulate that state. And, importantly, that encapsulation boundary also exists between superclass and subclass. Conceptually, from the perspective of the superclass, a subclass is client code just like any other client code from which the internal state of the superclass instance has to be protected.

Hence there needs to be a concept of dedicated initialization functions to guarantee that instances are always properly constructed and client code outside the class can’t end up with a half-constructed object and/or see an object in uninitialized state. And with respect to a superclass, the code of a subclass is “outside the class”.

➕ show 1 reply
quietbritishjim • today at 4:14 PM

There's really two things in play here.

One is that C++ has constructors, with lots of rules about which one is called when.

But the other is that primitive objects can sometimes be uninitialised, and sometimes that's what you want for performance (if you're about to overwrite them anyway). C++ classes are meant to be able to do anything a primitive type can (as a sibling comment says) so you sometimes want a class that you can either leave uninitialised or value initialise (essentially, set everything to zero) decided at the call site (not in the class declaration).

If C++ guaranteed that all members always had to be initialised, then all the default-like constructors (Foo x; Foo x = {}; Foo x = Foo(); etc) would resolve to the same thing (a call to the constructor you explicitly wrote if you did; otherwise all members default constructed, resolved as zero-initialisation if that's equivalent).

pjmlp • today at 4:05 PM

Because in languages like C++ and Swift, contrary to your other examples, the goal is that library types should be able to do everything that built-in types expose.

Thus you need all mechanisms to implement the same capabilities, thus constructors, by the way they are not alone in this approach.

➕ show 3 replies
pwdisswordfishq • today at 6:37 PM

Indeed. And forcing all object creation to be routed through the "constructor" concept leads to a whole host of problems. For example:

    std::vector v("foo", "bar");
This should create a vector of two elements, right? Well, too bad; it crashes instead. Why? Because the inferred type is std::vector<char>, and it attempts to construct a vector from a pair of iterators. Why? Because the only way to distinguish between different modes of constructing an object is through overloading, and overloads are too often ambiguous.

Arthur O'Dwyer's crusade against CTAD (<https://quuxplusone.github.io/blog/tags/#class-template-argu...>) ultimately boils down to this problem, which is not really type deduction itself, but ambiguous overloads, which are hard to avoid in the presence of constructors without resorting to clumsy workarounds like tag types (which create problems of their own).

There are other problems too, like the fact that you cannot call std::make_unique (or emplace) for a class with a private constructor even in a scope where you have access to the constructor itself.

➕ show 2 replies
lefty2 • today at 5:24 PM

I usually need to use a Init() function to initialised the member functions, because they are initialised with data that isn't available when the constructor is called, making it largely redundant. Another thing, just because a feature exists in a language doesn't mean you need to use it. Use it if it makes sense for your use case, otherwise don't use it.

xscott • today at 7:20 PM

I'm not praising C++ at all, but constructors serve as more than just a factory for the instances. The full comparison with Rust might be vs implementations of the Default, Into / From, Copy, and Clone traits in addition to ::new. (Maybe some others I missed too)

When I used to program in C++, my general rule was that applications follow the "rule of zero" (no explicit constructors), and libraries do what's needed to make the rule of zero work for applications.

➕ show 1 reply
raegis • today at 7:36 PM

30+ years ago it was easy to memorize all the rules for constructors, and much of the language itself. The improvements and additions over the years make it much harder.

marcosdumay • today at 4:17 PM

The thing you are annoyed about in C++ is not constructors. It's the overloading of syntactic operations.

The C++ design bets heavily on that. Just like you can overload an operator, you can also overload the meaning of `=`, `new`, variable declarations, and etc. That necessarily leads to an awful complex language, but also a very powerful one that can potentially lead to very easy to read code in high abstraction levels.

The problem both C++ and Swift have is that you can't really build high abstraction levels, because the languages are designed in a way that makes some fixed concerns creep over your entire code.

➕ show 1 reply
binary132 • today at 4:33 PM

I was surprised reading these comments to see hardly any mention of type invariance, and no mention at all of RAII. RAII gets you type invariants that hold for the entire lifespan of an object, and if anything goes wrong during initialization, you are guaranteed to release all partial state according to its specified rules — giving you something closer to whole-program invariants. We all love POD / structs, but they don’t get you that part, and doing it without RAII can land anywhere from a bit of meticulous bookkeeping all the way to building an intractable metaprogramming malebolge just to get half-baked DIY RAII.

➕ show 1 reply
badpun • today at 6:02 PM

The idea behind constructors is to preserve object's invariants (e.g. that a circle radius must be positive). In a language without constructor, if you initialize an object (allocate some memory and point to it) and only then fill its fields with some static function, it will contain potentially illegal state until you do.