Re: [Vala] [Genie] instance creation order


2010/1/6 Arc Riley <arcriley gmail com>:
Why does a class's init method get called before its construct method?
First, I'm not sure about genie's init vs construct, but if I
understand correctly, your short answer is : use Object(property:
value) instead of property = value (and maybe mark your property as

This seems very counter-intuitive to me given the limitations on the
construct method;
I've seen a difference recently, it may be because of the recent
change of construct properties.

GObject construction needs to be well explained (I'm not sure this is
100% accurate, but it gives a good idea, any corrections are welcome)
There is :
* the creation method (I'm not sure if this is the init or construct
block in genie) takes parameters and sets properties, they can cain up
to any base class creation method provided that it isn't [CCode
(has_construct_function=true)] (in practice this means either a class
written in vala, or GLib.Object).
* The constructor (construct block in vala) is called *from* the
creation method, and -here is your problem- you need to set the
properties you need before it's called. The only properties that are
guarenteed to be set on construction are construct properties, and the
preferred (only?) way to set them is by chaining up to GLib.Object.

A *construct* block is used to define a creation method which requires
parameters at construction time when being instantiated via the new
so it's not the same as vala.
operator. Creation methods are limited to setting the properties of the
class and may perform no other task (an init block should be used to perform
any other type of initialization). A class can have many creation methods
with either different names or different parameters. A default creation
method without any parameters is always available if no explicit creation
method is defined.

Since init runs first, none of the initialization code has access to
parameters passed to it by the new function.  Say, for example, an argument
passed is a parent container for the new instance to add itself to - all the
construct method is allowed to do (if I read this correctly) is set
self._parent which only happens after init has run.
As explained above, the init block runs as soon as you chain up, so
you need to chain up to GLib.Object to set construct properties rather
using assignment.


P.S. we need to start a wiki page about gobject construction like the
one on memory management.

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]