I try to create a simple derivable type but i seem to miss something. When i try to call the virtual method, "MY_ITEM_CLASS(result)" throws the critical error.
Compile with
gcc `pkg-config glib-2.0 gtk4 --cflags` test_gtk.cpp -o test_gtk `pkg-config glib-2.0 gtk4 --libs` -lstdc++
The error message is
GLib-GObject-CRITICAL **: 16:01:24.795: invalid unclassed type '(null)' in class cast to 'MyItem'
#include <glib-object.h>
#include <iostream>
typedef struct _MyItem MyItem;
#define MY_TYPE_ITEM (my_item_get_type())
G_DECLARE_DERIVABLE_TYPE(MyItem, my_item, MY, ITEM, GObject)
struct _MyItemClass {
GObjectClass parent;
void (*print)(MyItem* self);
};
typedef struct {
const char* name;
} MyItemPrivate;
auto static my_item_init (MyItem *object) -> void;
auto static my_item_class_init (MyItemClass* klass) -> void;
G_DEFINE_TYPE_WITH_PRIVATE (MyItem, my_item, G_TYPE_OBJECT)
auto static item__print(MyItem* self) -> void {
auto priv = (MyItemPrivate*)my_item_get_instance_private(self);
std::cout << (priv->name?priv->name:"unnamed") << std::endl;
}
auto static my_item_init (MyItem *object) -> void {
auto priv = (MyItemPrivate*)my_item_get_instance_private(object);
priv->name = "This is my name";
}
auto static my_item_class_init (MyItemClass* klass) -> void {
GObjectClass *object_class = G_OBJECT_CLASS(klass);
klass->print = item__print;
}
auto main() -> int {
auto result = (MyItem*)g_object_new(MY_TYPE_ITEM, nullptr);
MY_ITEM_CLASS(result)->print(result);
g_object_unref(result);
return 0;
}
It does not work because instead of
MY_ITEM_CLASS(result)->print(result);
it must be
MY_ITEM_GET_CLASS(result)->print(result);