Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

   > Yet, this prevents a bug where the base constructor can
   > call a virtual method that you override, and might not
   > be ready to handle. So eventually I just learned to
   > embrace and love this capability.
But this merely means that sub-classes cannot call functions (virtual or not) of their base class, since the base class is not yet initialized. It's not clear it is a net benefit. I have called base-class non-virtual functions a few times in the past, so this is not purely theoretical.

The correct solution would be for a language to have two-phase initialization. In the first phase you cannot call virtual functions, it would be a compile-time error. In the second phase, you can, as everything has been initialized already.

(You can have a poor-man version of this with static create() or make() functions and private constructors in C++ and similar languages.)



  // This is valid swift:
  class MyClass: MyBaseClass {
     let someVar: Int
     init() {
         // initialize member vars
         self.someVar = 99
         // call base constructor
         super.init()
         // we are now completely initialized
         self.anyFunction()
     }
  }




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: