What is a Constructor

I am just cleaning up the Nim language bindings a bit fixing a minor bug, and I noted that I have never seen an exact definition of the difference of a constructor vs an ordinary method.

So what are the promises of a constructor like gtk_button_new()?

  • function name contains “new”
  • functions has a none void return value, which is not a basic type like float, int, char…

Constructors can have parameters, even OUT parameters. Is it guaranteed that the return value is really newly allocated/created, or can it be an existing object cached in GTK (this is important to handling proxy objects of the foreign language.)



The annotated symbol should not become available as a static methods but as a constructor.


Is it guaranteed that the return value is really newly allocated/created

Now I think that this is indeed true! That would simplify the bindings a bit :slight_smile:

There’s not really any difference between constructors and other functions other than how you might map them to your target language. If your target language has a concept of constructors then you’d map them to that instead of e.g. static methods.

It would be surprising for a constructor to return a previously created object so if that helps anything in your bindings then it seems safe to assume that this never happens (and assert on that!), but it shouldn’t really matter for bindings. Other functions can return new objects / previously created objects as well and you would have to handle both cases there anyway, so doing the same for constructors shouldn’t make much of a difference.

Generally you would handle them exactly like any other method and build the bindings based on the introspection data.

Note that for any GInitiallyUnowned it’s still “transfer floating” aka “transfer none” because of historical reasons, and you’re supposed to call g_object_ref_sink() on the return value.

“out” parameters are to be handled like in any other function and you’ll have to work based on the introspection data you get.

1 Like

In bindings for SML, a language that has no object-oriented concepts, the single-inheritance class hierarchy is encoded in the type system. Given the strong static typing of SML, the ‘constructor’ status of a function is used to override the return type to be the the type of the class containing the constructor because, in many cases, the return type in introspection data is the type for an ancestor class, e.g. for Gtk.Button.new introspection data says the return type is a Gtk.Widget. Apart from that a constructor is treated like any other function.

1 Like

Indeed. That’s the same for the Rust bindings and probably most other bindings for statically typed languages.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.