Pointer returning void working in C but not in C++

I am trying to make a Native C/C++ app for Tizen platform and this a part of the code of a template Tizen Studio gives : (Note this is C code)

static char*
gl_text_get(void *data, Evas_Object *obj, const char *part)
{
    char buf[1024];
    item_data *id = data;
    int index = id->index;

    if (index == 0)
        snprintf(buf, 1023, "%s", "Email Inbox");
    else if (index == 1)
        snprintf(buf, 1023, "%s", "[email protected]");
    else if (!strcmp(part, "elm.text"))
        snprintf(buf, 1023, "%s", genlist_demo_names[index - 2]);
    else if (!strcmp(part, "elm.text.1"))
        snprintf(buf, 1023, "%s", "Re: Long time no see");
    else
        snprintf(buf, 1023, "%s", "Hello~! how have you been?");

    return strdup(buf);
}

static void
gl_del(void *data, Evas_Object *obj)
{
    item_data *id = data;
    if (id) free(id);
}

static void
gl_selected_cb(void *data, Evas_Object *obj, void *event_info)
{
    Evas_Object *label;
    Elm_Object_Item *it = event_info;
    appdata_s *ad = data;
    elm_genlist_item_selected_set(it, EINA_FALSE);

    label = create_label(ad, it);
    //View changed to text detail view.
    elm_naviframe_item_push(ad->nf, elm_object_item_part_text_get(it, "elm.text"), NULL, NULL, label, NULL);

    return;
}

And this templates successfully compiles and runs on my Tizen device. However, when I copy this same code in a C++ file (because I need some cpp-only features in my project). Compilation fails :

And this is seems quite obvious to me since a pointer cannot pick-up the value of void. So why is this working in C code ? Has void the same meaning in C and C++ ?

Answer

In both C and C++, any pointer type is implicitly convertible to void*.

But in C only, void* is implicitly convertible to any other pointer type, whereas in C++ that is not the case, you need an explicit type-cast instead, eg:

Elm_Object_Item *it = (Elm_Object_Item *) event_info;
appdata_s *ad = (appdata_s *) data;
item_data *id = (item_data *) calloc(sizeof(item_data), 1);

Or, more preferably, using static_cast instead of a C-style cast:

Elm_Object_Item *it = static_cast<Elm_Object_Item*>(event_info);
appdata_s *ad = static_cast<appdata_s*>(data);
item_data *id = static_cast<item_data*>(calloc(sizeof(item_data), 1));

Leave a Reply

Your email address will not be published. Required fields are marked *