Skip to main content

Ralsina.Me — Roberto Alsina's website

Now I remember why I don't like C++

I have refactored IUP/Qt into a lovely object hierarchy. And I now remember why I dislike C++.

Here's the basic problem (code may be wrong, I don´t have the broken versions anymore):

I have a base class IObject, that has stub setters/getters for all the IUP attributes.

For each kind of widget, I create a class that inherits from IObject and the matching Qt widget (example: QDialog).

These have to be hooked into an Ihandle structure through the use of a void * (remember, that's C, I have that too ;-)

Now, this was my first naive approach:

Ihandle *n;
IQDialog *d=new IQDialog();
n->handle=d; //handle is a void*

That compiles ok. However, when you try to call a d member later (and I know I am using old C casts... they had worked for me until today!) ...

((IObject *)(n->handle))set_title("Title here");

Blammo, segfault. Why? Because in one of the assignments to/from void *, the pointer for some reason starts to point elsewhere.

Here´s what Gliptic at #C++ suggested, and it does work:

Ihandle *n;
IQDialog *d=new IQDialog();
n->handle=static_cast <void *>(static_cast < IObject *> (d));

Right, I have to cast it twice.

And here is how you get it back:

(static_cast < IObject * >(n->handle))->set_title ("Some title");

Isn't this just ridiculously weird for anyone coming from any other language?

Or am I missing something completely?

But the good news is, it works ok, and the Qt backend now has a decent structure to hack on.


Comments powered by Disqus