3 ms·
> Part of the contract for objects is that you can't interact with an instance before its constructor has run, This contract doesn't hold anyway, because you c
by pkolaczk 4y ago
> Part of the contract for objects is that you can't interact with an instance before its constructor has run,
This contract doesn't hold anyway, because you can call object's methods from the constructor before the object initialization finishes, and those methods can even call the overriding code in the derived classes. So even though `super` is guaranteed to be initialized fully, `this` is not.
- kevincox 4y agoInterestingly C++ avoids this problem by making virtual method calls use the vtable of the currently constructing type. So for example if you have Super and a subclass Sub. When Super's constructor is running it won't call a method of Sub. Once the parent constructor completes the new vtable is then used. So you can think that the object starts life as a Super then becomes a Sub after the Super constructor finishes. It is complicated and I'm sure it has caused some bugs, but it has also solved some bugs.
- int_19h 4y agoIt also works that way in reverse when objects are destructing, and applies to dynamic_cast in addition to vtable dispatch. While the idea is reasonable on its face, it's convoluted enough in practice that it used to be a common source of interview gotchas, so I'm not sure that it fixes more problems than it creates in practice.