Search code examples
valagobject

How does vala allow defining GObjects with no default constructor?


The Vala tutorial shows that classes can be written with constructors either in GObject style, or in a style similar to Java / C# etc.

The tutorial shows that this is completely independent of whether the class inherits from Glib.GObject or not. (EDIT: I was confused by the tutorial switching between Glib.Object and Object. In Vala there's an implicit using Glib, so the two are the same).

Am I right in thinking that if a Glib.GObject subclass is defined without a default constructor (using Java/C# style), an implicit default constructor will have to be defined for GObject, presumably leaving all fields filled with binary zero (as per GObject initialization)?

See also Initialize a GObject with parameters which are not GObject properties?


Solution

  • Vala will automatically create a constructor in the C code. This follows the *_new naming pattern. So the simplest example:

    void main () {
        new ExampleWithoutExplicitConstructor ();
    }
    
    class ExampleWithoutExplicitConstructor {
    }
    

    If you compile this with valac --ccode example.vala and look at the resulting C code you will see _vala_main calls example_without_explicit_constructor_new () and this then calls example_without_explicit_constructor_construct (). example_without_explicit_constructor_construct () then calls g_object_new () for that type. As part of g_object_new creating the type it will call example_without_explicit_constructor_instance_init () where any variables can be initialized.

    Here is a more complex example that inherits from Object, so is a full GObject class, has a field with a default value and a property with a default value:

    void main () {
        new ExampleWithoutExplicitConstructor ();
    }
    
    class ExampleWithoutExplicitConstructor:Object {
        private string example_field = "default";
    
        public string an_object_property { get; 
            set; 
            default = "this object properties default string";
            }
    }
    

    You will notice from the C code that the _new, _construct, g_object_new, _instance_init pattern is the same. What Vala has done is set the _instance_init to initialize the default values for the fields and properties.

    Public fields without default values are null. You will see they appear in the definition of the struct that holds the instance data. Private fields are similar, but held in a private struct for the instance. You can see this for yourself by playing around with the example.