Search code examples
coopglibgobject

How to create a GObject final class with both public and private members?


In the chapter Boilerplate code of GObject Manual, when ViewerFile is declared as a final type using G_DECLARE_FINAL_TYPE, how can we add public data to it since it is hidden behind the viewer-file.c which is not included?


Solution

  • The main distinction between a "derivable" GObject type and a "final" GObject type is the visibility of the instance data structure.

    If the GObject type is "derivable" then you can only use a private instance data structure, as the instance structure is public and it's generated to just include the parent's structure.

    If the GObject type is "final" then you only get instance fields, since the instance data structure is private to your C source file.

    You cannot mix the two approaches, unless you decide not to use the macros and write the boilerplate by hand.

    Additionally, you should not ever access fields on an instance data structure; provide accessor functions, instead, so that you can validate pre-conditions and post-conditions safely.