Remix.run Logo
▲ layer8 4 hours ago

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); 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 leave the object in an invalid 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”.

▲pwdisswordfishq 4 hours ago | parent [-]

Rust allows establishing invariants on its types without having a designated "constructor" concept. It accomplishes the same with the equivalent of static methods. Constructors are simply unnecessary.

▲steveklabnik 3 hours ago | parent | next [-]

Two things make this possible, really: the first is that Rust doesn't have subclassing, so one classic reason for constructors doesn't exist. The second is Rust's privacy system, which makes it so that external users can be forbidden to use the literal syntax to create a struct. This is what lets you guard creation to preserve invariants.

One useful feature of constructors still doesn't exist, which would be the placement new style thing, but that's on its way as well, and is an optimization rather than a requirement for most cases.

▲layer8 3 hours ago | parent | prev [-]

Rust doesn’t have implementation inheritance. If it did, it would need a constructor-like concept as well.

▲gpderetta 2 hours ago | parent [-]

With guaranteed RVO you could do something like this (pseudo-C):

   struct FooBase { ... }
   fn make_foo_base(...) -> FooBase
   struct Foo { base : FooBase; ... }
   fn make_foo(args...) -> Foo {
      return { .base = make_foo_base(...), ... }
   }