munificent / craftinginterpreters

Repository for the book "Crafting Interpreters"
http://www.craftinginterpreters.com/
Other
8.99k stars 1.05k forks source link

Design question - running parent initializers #963

Closed TKharaishvili closed 3 years ago

TKharaishvili commented 3 years ago

Greetings Bob,

First things first, a huge thanks for writing this book and making it available, it's something I wish I had years ago.

Let's consider the following piece of Lox:

class A {
    init() {
        print "Init A";
    }
}

class B < A {
    init() {
        print "Init B";
    }
}

B();

Running this only prints "Init B", the parent initializer doesn't get called. This was a little unexpected to me, 'cause the languages I'm familiar with handle it differently:

My question is - is this by design? And if so, what's the line of thought behind it? I would think that running parent initializers(either automatically or by making them mandatory) would be important for proper object construction...

I tested this with your version of jlox as well as my own implementation. I also had a quick second look at the inheritance chapter to see if I there is a mention of it. I hope I didn't miss something obvious...

munificent commented 3 years ago

My question is - is this by design?

Yes.

And if so, what's the line of thought behind it? I would think that running parent initializers(either automatically or by making them mandatory) would be important for proper object construction...

You're absolutely right. In a more principled language, we would make sure that superclass initializers were always called. I didn't for Lox mostly to keep the language a little simpler. It's hard to make a language small enough to fit two complete implementations in one book (and I certainly didn't end up with a small book as it is) so there are a couple of places where the language isn't as robust it would otherwise be in order to avoid spending pages on features that would make Lox a better language but that aren't very interesting to implement.

(This is also why Lox doesn't have arrays/lists, lambdas, private fields, etc.)

TKharaishvili commented 3 years ago

That makes sense. Thanks for clarifying. And thanks for doing all of this really, writing the book itself is large enough a task to take on, not to mention responding to hundreds of issues here.

Closing this one.