Search code examples
cgobject

GObject: how to check non-initialized pure virtual at compile time?


Is there any way in the GObject world to detect uninitialized pure virtual function at compile time?

I'd like to call a pure virtual method without checking it first.

/* pure_virtual_method must be non NULL */
base->pure_virtual_method();

But if it's not initialized, it will just SegV.


Solution

  • I don’t believe there is a way to perfectly check this at compile time, as (for example) your code could be linked into another library, a subclass derived from your class which defines the virtual method, and the implementation of the virtual method set to NULL (explicitly, or implicitly through not initialising it) in the subclass.

    The conventional way to handle this is at runtime: g_assert (base->pure_virtual_method != NULL); base->pure_virtual_method ();

    Some static analysis tools may be able to check this g_assert() constraint at compile time, although given the highly dynamic nature of subclassing in GObject, that’s unlikely.