1

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;
}
3
  • This seems more like c than c++. Like typedef struct _MyItem MyItem; etc Commented Apr 6, 2024 at 15:35
  • @user12002570 It is mostly C, largely because the code uses Glib (C library) instead of glibmm (C++ wrapper). On a related note, since it uses the g_object_* functions instead of Glib::Object, the "glib-object" tag looks inaccurate. I'll change it to a more accurate tag. Commented Apr 6, 2024 at 16:13
  • Looking at the history, this question was originally tagged for C instead of C++. Given that the question is about using a C library, the C tag would be good, if only the code did not use C++ features. If you replace <iostream> usage with C-style output and replace auto with explicit types, you could try again with the C tag. (Did I miss any other C++-isms?) Commented Apr 6, 2024 at 16:20

1 Answer 1

1

It does not work because instead of

MY_ITEM_CLASS(result)->print(result);

it must be

MY_ITEM_GET_CLASS(result)->print(result);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.