Monday 3 October 2011

Overloaded constructors and inheritance - F#

I've been struggling vainly to create my own Exception class but the obvious fails to compile:


type MyException1 () =
inherit Exception ()
new (msg:string) = {inherit Exception(msg)}


with the following error message:

      new (msg:string) = {inherit Exception(msg)}
  -----------------------^^^^^^^^^^^^^^^^^^^^^^^^

stdin(9,24): error FS0762: Constructors for the type 'MyException1' must directly or indirectly call its implicit object constructor. Use a call to the implicit object constructor instead of a record expression.

After some head-scratching, I guessed that the problem might be the default constructor, and lo, this works.


type MyException =
inherit Exception
new () = {inherit Exception()}
new (msg:string) = {inherit Exception(msg)}


It's not clear to me why I need to explicitly define the default constructor, but the compiler has stopped complaining now.

No comments:

Post a Comment