Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dlang: why are constructors not inherieted?

Is there a way to not have to repeatidly write this(parent class args) {super(parent class args);} when the arguments are exactly the same?

The code:

class Parent {
  string name;

  this(string name) {
    this.name = name;
  }
}

class Child : Parent {
}

unittest {
  auto child = new Child("a name");
  assert(child.name == "a name");
}

https://run.dlang.io/is/YnnezI

Gives me the compilation error:

Error: class onlineapp.Child cannot implicitly generate a default constructor when base class onlineapp.Parent is missing a default constructor
like image 433
tirithen Avatar asked Jan 01 '23 12:01

tirithen


1 Answers

Java and C# don't inherit constructors either (unless that's changed in the last few years - I don't think C++ allowed it either until c++11), and D follows the same reasoning so you can read more by looking up things about them.

Basically though the reason is that subclasses must have their own unique state - at very least stuff like the vtable even if you don't declare any of your own variables - and thus a unique constructor is required. Otherwise you can have uninitialized members.

And if inheritance went the whole way, since Object has a this(), new AnyClass(); would compile and lead to a lot of invalid objects. (In regular D, if you declare any ctor with arguments, it disables the automatically-generated zero arg one.)

Now, D could in theory do what C++ does and auto-generate other args too... it just doesn't. Probably mostly because that is a relatively new idea in C++ and D's class system is primarily based on Java's older system.

But all that said, let me show you a trick:

this(Args...)(auto ref Args args) { super(args); }

stick that in your subclass and you basically inherit all the parent's constructors in one go. If the super doesn't compile for the given args, neither will this, so it doesn't add random things either. You can overload that with more specific versions if needed too, so it is a reasonable little substitute for a built-in language feature.

like image 95
Adam D. Ruppe Avatar answered Jan 13 '23 11:01

Adam D. Ruppe