Some comments on :help E1377 (subclassing and constructors)

17 views
Skip to first unread message

Lifepillar

unread,
Feb 20, 2024, 2:17:23 PMFeb 20
to vim...@googlegroups.com
:help E1377 has this paragraph:

Unlike other languages, the constructor of the base class does not
need to be invoked. In fact, it cannot be invoked. If some
initialization from the base class also needs to be done in a child
class, put it in an object method and call that method from every
constructor().

That seems accurate, as in the following script `Bar` has its own
(implicitly defined) constructor, and the parent's constructor is not
invoked (no message is printed):

vim9script

class Foo
var _y = 0

def new(this._y, z: string)
this.Init(z)
enddef

def Init(z: string)
echomsg $'y={this._y}, z={z}'
enddef
endclass

class Bar extends Foo
endclass

var bar = Bar.new(1) # Sets _y to 1, doesn't print anything

Now, I have a couple of remarks:

It seems a bit counterintuitive that `Bar` cannot be initialized like
`Foo`, but with either `Bar.new()` or `Bar.new(n)`.

It may be the case that `Init()` does something necessary for the
initialization of the object. But `Bar` does not call `Init()`, so `bar`
may be potentially broken.

Ok, all that is as documented and can be remedied, of course:

class Bar extends Foo
def new(this._y, z: string)
this.Init(z)
enddef
endclass

var bar = Bar.new(1, 'a') # OK

But:

- I have basically redefined the same constructor of the superclass;
- I must know the private members of `Foo` to do that;
- I must be aware that any constructor must call `Init()` for the
correct initialization of the object. Again, I must know an
implementation detail of the superclass.

Note that `Foo` may be a library object imported by arbitrary users in
arbitrary scripts.

Wouldn't it make more sense for `Bar` to have the parent's constructor
as a default?

Thanks,
Life.

Reply all
Reply to author
Forward
0 new messages