When to use get_instance_private() and when to access directly the struct

Hi all:

I was checking the GtkPaned() code in Gtk4 and found this:

  if (child)
    {
      paned->start_child = child;
      gtk_widget_insert_before (child, GTK_WIDGET (paned), paned->handle_widget);
    }

The point is that I don’t understand why is the start_child (and other) elements being stored in the public part of the class (although the structure itself is in the .C file and, thus, isn’t accessible from the exterior), instead of creating a private structure instead. Is it only for historic reasons and any new class should always put the private properties in the Private structure? Or am I missing something?

Thanks.

If the instance structure is private, there’s no point in going through a private data structure: it’s just needless indirection.

The reason we put things into private structures is to avoid direct access from external users.

But then, why does xxx_get_instance_private() exist, if private data can be put directly in the structure, and public properties should be accessed through the get/set system?

Or is it only needed in derivable types? Does that mean that is not possible to do a class derived from GtkPaned?

Derivable types must have their instance data structure defined in a public header, in order to allow other types to derive from them. This is why private instance data exists: to avoid putting fields in the public instance structure, where they can be accessed directly.

Final types, like GtkPaned in this case, are not derivable: their instance structure is merely declared in a public header, but defined in the source code. This means they don’t need a private data structure.

1 Like

Ok, that was what I was missing then: GtkPaned is not derivable.

Thanks!!!

Reviewing the code I have another question: GtkPaned, in Gtk3, was derivable, but it has been changed to non-derivable in Gtk4. I presume that this means that it is not possible to do a new GObject class that inherits from GtkPaned in Gtk4… If this is the case, why did you changed that?

And if it isn’t the case and it is possible to inherit from GtkPaned in Gtk4, then… what is the difference between a derivable and a non-derivable class?

It’s part of a larger design goal of making GTK’s type hierarchy more flat, and preventing people from breaking the toolkit, or the toolkit breaking applications.

A derivable class can be derived to make your own types; a non-derivable one cannot.

GTK still has derivable types—like GtkWindow, or GtkWidget. Most “leaf” widgets, and most container ones, have been made final. In the case of basic containers, we also provide layout managers, which encapsulate the layouting code of the widget as an ancillary object that can be used as a delegate, instead of using subclassing.

1 Like

Now it makes sense. Thanks!

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