Why don't constructors have override checking?

submited by
Style Pass
2025-01-23 00:00:14

It’s interesting because you define initialize as an instance method, but then you call a new as a singleton class method. We can do some digging to figure out how that works:

A nil source_location usually means it’s a method defined in the Ruby VM, so the easiest thing is to grep the Ruby VM source code:

The alloc method asks the garbage collector to allocate memory for the new instance (but does not initialize it). Then with an instance in hand, Ruby can dispatch to the initialize instance method.

If the class doesn’t implement an initialize method, the dispatch goes all the way up to BasicObject#initialize, which takes no arguments and returns nil.

These numbers like #7 and #11 are references into the constant pool, which is basically like static data in a class file. You can see the whole pool with javap -v instead of javap -c, but it’s long and basically just shows what’s in the comment so I omitted it.

The “allocate memory” step and the “initialize the instance” step are separate bytecode instructions (new vs invokespecial). In Ruby, there’s only one bytecode instruction (the call to the .new method), and the logic is hidden behind that method call. But otherwise, they both have these two steps.

Leave a Comment