5

I'm new to Vala and so far I think it's pretty cool but I'm having trouble understanding inheritance. I read here that I should use base() to call the parents constructor. Alright, cool, seems understandable but It din't work for me. I kept getting the error on the title. Here is my snippet to show:

public class MyBox : Gtk.Box {
    public MyBox(Gtk.Orientation orientation, int spacing) {
        // I have to this
        this.set_orientation(orientation);
        this.set_spacing(spacing);
        // I want to do this:
        base(orientation, spacing);
        //workaround is this:
        Object(orientation: orientation, spacing: spacing);
    }
}

Please help me understand why Object(....) works but not base(...)

Shouldn't it be the same thing?

RandomGuy
  • 419
  • 4
  • 14

1 Answers1

7

This is due to implementation of the C code. When Vala generates a constructor, it generates two C functions a _new function that allocates memory and calls the _construct and a _construct function that initialises the object. When you case the base constructor using base(), it needs a matching _construct function to call. Not all the classes written in C have this; in the VAPI file, you will find has_construct_function = false for some constructors. If this is the case, no chain-up can be done. The base GObject can set properties from arguments, so this becomes the only way to set defaults in the base class.

apmasell
  • 7,033
  • 19
  • 28
  • That was a perfect explanation. So whenever I get a chain up error, this would be **only** way to resolve it? – RandomGuy Apr 26 '15 at 20:01
  • 2
    Yes. In the case of those constructors, the parameters are the same as passing them by name to the `Object` constructor, so it's not lacking any functionality. – apmasell Apr 28 '15 at 11:59