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 <i>tons</i> of rules you need to memorize (Swift's "convenience" vs "designated" initializers are a real treat to unpack).<p>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.<p>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.<p>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.)
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.<p>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.<p>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”.
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.<p>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:<p>- 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.<p>- 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.
But C++ has the return value optimisation (even the named return value optimisation), where you construct an object in a function and then "return" it, but it's actually constructed in place at the call site (not guaranteed but allowed by the language and widely implemented):<p><pre><code> Foo make_foo() {
Foo result;
result.blah = 7;
return result;
}
Foo f = make_foo();
// Equivalent to:
Foo f;
f.blah = 7;
</code></pre>
I don't know enough about Rust to know whether it has the same thing, but surely it could? If anything, it feels like it ought to be easier (for the compiler) because Rust moves rather than copies by default, and moves are destructive and bytewise.<p>Given that, it seems like a language could be designed so that a static method that returns an object could be allowed to construct an object in place. Again, I don't know enough about Rust or Zig to know if that's true of them.
Rust doesn't really have a good answer for guaranteed copy elision or in-place initialization at the moment. The devs are working on it, though (<a href="https://github.com/rust-lang/rust/issues/153825" rel="nofollow">https://github.com/rust-lang/rust/issues/153825</a>).
> not guaranteed but allowed by the language and widely implemented<p>Ome can make it guaranteed (assuming Foo is an aggregate) by writing:<p><pre><code> Foo make_foo() {
return Foo{.blah = 7};
}
</code></pre>
This guarantees initialization happens at the end of the function, since you are returning a pure rvalue. Generally a good style rule to adopt and no annotations needed.
right, first-class support for a special say "must_construct_inplace" keyword on a function returning an object would be an interesting language design direction...<p>What happens inside<p><pre><code> must_construct_inplace Foo make_foo() { ... }
</code></pre>
can be as "inefficient" as your example above, but the compiler would validate & figure out a way to make it an in-place-construction, guaranteed RVO.<p>(similar to `constexpr` validation)<p>EDIT: Looks like this already exists under several names ("build-in-place", "placement by return", "result location semantics") in Ada's `return W : Widget do ... end return;`, Carbon's returned var c: Circle; ... return var;`, and Rust has (still open) RFC 2884 "placement by return", and Zig seems to have this fully built-in via result location semantics?!
> However, create-and-return makes in place construction difficult<p>This is definitely the closest thing to an answer in this thread. This is something that languages without constructors do struggle with, yes, and as other commenters pointed out, Rust sees this as a performance issue and is working on it.<p>Thanks for the informative reply.
Agree. C++17 lets you write factory functions that directly return `T(args...)` and can initialize an `auto foo = make_t();` so in many cases the distinction between rust and modern c++ is diminished.<p>But still, doing `std::make_unique<T>(args...)` or allocates storage and guarantees to run T's constructor there, and you can even do `std::optional<std::mutex> slot; slot.emplace();` which builds the mutex inside the optional even though a std mutex can't be moved or copied.
Indeed. And forcing all object creation to be routed through the "constructor" concept leads to a whole host of problems. For example:<p><pre><code> std::vector v("foo", "bar");
</code></pre>
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.<p>Arthur O'Dwyer's crusade against CTAD (<<a href="https://quuxplusone.github.io/blog/tags/#class-template-argument-deduction" rel="nofollow">https://quuxplusone.github.io/blog/tags/#class-template-argu...</a>>) ultimately boils down to this problem, which is not really type deduction itself, but ambiguous overloads, which are hard to avoid when constructors are the only way to create an object, without resorting to clumsy workarounds like tag types (which create problems of their own).<p>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.
Yes, the ergonomics are just better<p>If you Vec::with_capacity(5) both you and a reviewer <i>know</i> what's going on here - this is clearly a Vec with capacity 5.<p>When you call a C++ constructor with 5 as the parameter, both you and the reviewer had better be sure what that 5 means.
These aren’t problems with the constructors per se, though. E.g. Java doesn’t have any of these problems.
Java absolutely does have the ambiguous overload problem.<p><pre><code> public class MyVector {
public MyVector(int... items) {
System.out.println(String.format("constructing a vector of %d items", items.length));
}
public MyVector(int start, int end) {
System.out.println(String.format("constructing a vector from the range [%d, %d)", start, end));
}
}
</code></pre>
How do you construct a MyVector of two items?<p>In JavaScript, how do you use new Array(...) to create an array consisting of a single integer? You can do the same with a single value of any other type.<p>The reason these languages don't have the make_unique or emplace problems is because they don't have a concept of in-place construction at all, since objects in those languages are heap-allocated and have reference semantics anyway.
Right, but that’s a relatively rare problem, and doesn’t usually result in crashes.<p>More importantly, you’d have exactly the same problem if you’d overload a regular method that way. So it’s a problem with overloading, not with constructors.<p>> How do you construct a MyVector of two items?<p><pre><code> new MyVector(new int[] { 23, 42 })
</code></pre>
The correct solution, of course, is to provide named static constructor methods instead.<p>I do agree that support for named actual constructor methods would be nice.
There's really two things in play here.<p>One is that C++ has constructors, with lots of rules about which one is called when.<p>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).<p>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).
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.<p>Thus you need all mechanisms to implement the same capabilities, thus constructors, by the way they are not alone in this approach.
That feels a bit like begging the question? Library types only need constructors to replicate built-in types if built-in types use constructors themselves. But <i>do</i> built-in types need constructors? What is lost by just using regular functions?<p>Also I was under impression that Rust at least has a similar goal?
I don't see the link between constructors and whether or not built-in types have special treatment. Care to enlighten the class?
In C++ you can write "int x;" and get an object of type int.<p>If the only way to initialise a class-type object was to call some custom static method on it then you'd have to write "Foo x = Foo::create();". Suddenly it looks more special than a built-in type.
In C++, `int x;` leaves the int uninitialized, which isn't really constructing at all. In rust (which I program in lately so I'll use it as the example) you simply can't use uninitialized variables in the first place without unsafe code, so the equivalent would either be:<p><pre><code> let x: i32;
foo(x); // compiler error
</code></pre>
or if you really wanted to use uninitialized memory,<p><pre><code> let x: i32 = unsafe { std::mem::uninitialized() }; // compiler warning
foo(x);
</code></pre>
which, in rust, can be done with any other type too (substitute i32 for any T and the above examples are identical.) I don't see anything different about built-in types here vs standard ones, other than the compiler has literals for the built-ins, which is more a consequence of rust not allowing <i>literals</i> for library types. But that's a very different discussion.<p>I guess the argument might be that for C++, they want the author <i>of the type</i> to determine whether the value should be left uninitialized on declaration/construction, instead of the caller. Which is... not exactly the semantics I would have chosen.
It is up to the constructor to only initialize storage, or do whatever it feels like to have values assigned to it.<p>Thus a default constructor replicates a plain <i>int x;</i>, whereas the copy constructor or single value constructor is used for <i>int x = 42;</i>.<p>By the way, already in the 16 bit days you could configure to have warnings as errors for variables being used without initialisation.
> It is up to the constructor to only initialize storage, or do whatever it feels like to have values assigned to it.<p>Right, see the "I guess the argument might be" part above... I find this to be a very questionable design choice, leaving you to have to go and read a header somewhere to determine whether `Foo f;` is safe or not. But it's not really a choice, is it? C++ <i>had</i> to do it this way to be compatible with how C programs were written back in the 1970s.<p>> By the way, already in the 16 bit days you could configure to have warnings as errors for variables being used without initialisation.<p>Ah yes, the "but C can be configured to be not-insane" argument, one of my favorite pjmlp-isms, right up there with "but $LANG's compiler is written in C++" and "but you already get memory safety with a GC". Keep on doing you!
Hmm interesting. Is there a way to "value initialise" (in C++ speak) an int in Rust to set it to zero? Like `let x: i32 = {};` (without explicitly writing `=0`)? How about a way to do that for a sort of plain struct where there are multiple members you just want to set to their default values?
Rust has a Default trait, if your type Goose <i>has</i> a Default then<p>let foo: Goose = Default::default();<p>Those "primitive" types have a Default, the integers default to zero, as do the floating point types, bool defaults to false, I believe an empty string is the default string (in both the sense that's the default for String, and the default for str, the string slice reference roughly analogous to C++ string_view)<p>Some things don't have a sane default, just as those things wouldn't provide a zero argument constructor in C++. There isn't a default file descriptor, a default network socket, and so on and so those types do not implement Default
Yep, that's std::mem::zeroed(), which just writes zeroes into the allocated memory regardless of its type... also only available in unsafe code.<p><pre><code> #[derive(Debug)]
struct Foo {
_i: i32,
}
fn main() {
let x: i32 = unsafe { std::mem::zeroed() };
println!("x={x}");
let f: Foo = unsafe { std::mem::zeroed() };
println!("f={f:?}");
}
</code></pre>
prints:<p><pre><code> x=0
f=Foo { _i: 0 }
</code></pre>
It's unsafe because if Foo contained a String, it would be string with a null pointer inside it and you'd crash trying to read it. If you want "Default" values instead of zeroed (ie. you don't want to run unsafe code), that's what the Default trait is for, and this becomes:<p><pre><code> #[derive(Debug, Default)]
struct Foo {
_i: i32,
}
fn main() {
let x: i32 = Default::default();
println!("x={x}");
let f: Foo = Default::default();
println!("f={f:?}");
}
</code></pre>
and prints the same thing.
But you can also write int x = rand(); how is that special?
If my understanding is correct, C++ built-in types can be declared without initializing them:<p><pre><code> int x; // Unitialized, garbage value
int x{}; // Value-initialized (falls back to zero-initialization)
</code></pre>
We want classes to have the same behaviour:<p><pre><code> Struct s; // Default-initializes (presumably we want members uninitialized)
Struct s{}; // Value-initializes (presumably we want members initialized)</code></pre>
As I replied in a sibling comment to yours, at least one language without constructors (Rust) has the exact same semantics for built-in types vs library types here. You must initialize in typical code, and the escape hatch is std::mem::uninitialized() which lets you work with uninitialized data, and this is true for any type, built-in or otherwise.
For many years now, <i>This function is deprecated. Use MaybeUninit<T> instead.</i><p>core::mem::uninitialized is of course unsafe, but what people who designed it hadn't really appreciated was that in most cases it was impossible to use it correctly, it almost might as well have been a call to core::hint::unreachable_unchecked<p><i>If</i> your type is a ZST then core::mem::uninitialized was safe to use, because not initializing zero bytes of RAM is the same as initializing all zero of them, this can't possibly matter so we're fine. Otherwise though, we create values which the LLVM backend is sure we cannot know and so it feels entitled to optimise as if any assumptions we make about those values are false, even if the results are contradictory. This causes immediate Undefined Behaviour all over the place.<p>The MaybeUninit<T> wrapper type is pretty easy to use and won't invoke Undefined Behaviour so long as you do everything in the instructions.
I literally had `MaybeUninit::uninit().assume_init()` first in the comment but rewrote it with `std::mem::uninitialized()` because I thought it would be more readable to a C++ crowd, but perhaps your right, I should have left it as-is.
MaybeUninit::uninit().assume_init() is, exactly like the deprecated core::mem::uninitialized() immediately UB unless your type is zero size and thus there's no difference between initialized and uninitialized.<p>You can unsafely ask for an uninitialized value of any type, but you <i>should not</i> ever assert that you've initialized it unless you actually have. Essentially, you can write this in Rust, but you need to be specific about what you're doing and when you are or are not initializing the variable or else things will go badly for you.<p>It wouldn't be <i>worse</i> in C++, historically, but C++ people are more used to their world being set on fire by an angry compiler because they did something wrong. In Rust you'd be quite surprised by the compiler's wrath.
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.
The thing you are annoyed about in C++ is not constructors. It's the overloading of syntactic operations.<p>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.<p>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.
I get that for C++ to have all this overloading it needs constructors, but Swift doesn't take the same bet as C++ does when it comes to overloading, yet it still has first-class constructors anyway. So do lots of other languages (Java, C#, TypeScript, etc.) Swift is especially interesting because it's basically a successor language to Objective-C, and Objective-C did <i>not</i> have first class constructors (`-init`/`-initWithFoo:` is just a convention), they chose to add it anyway.
The convenience vs. designated initialization in Swift is exactly the same kind of attempt to overload normal language syntax.<p>Outside of that, Swift has only normal OOP constructors, that are something completely different, and almost not a pain at all. Normal constructors are just a control layer on top of memory initialization that lets you write custom rules for it. It becomes necessary when you have protected memory in your objects, because the external code can't just go and set it, but even languages like Python understand it's convenient to have a defined place to set things up.
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.
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.