I'm using QT 5.7 and, because of the libraries I have to use, I need to convert a QObject ('s derived class) to and from a void pointer.
A couple of definitions. I have a function that accepts only a void pointer, and my class derives from QObject:
void oneFunction(void *obj);
class MyObj : public QObject
MyObj *ptr = new MyObj(parent);
void callbackFromOneFunction(void *theOldPointer)
MyObj *oldPtr = qobject_cast<MyObj*>(static_cast<QObject*>(theOldPointer));
if (oldPtr != nullptr)
... Now it's back, so use it
I think a single
static_cast is enough.
static_cast doesn't check the type at runtime and should be used when you're sure the type is okay. In this case you're sure, and you won't need
qobject_cast checks the type at runtime (it's similar to
static_cast or C-style cast is okay. Although C-style cast works fine here, it's not recommended because:
static_casts are far more readable and can be searched for more easily.
When the source type is
QObject * or its derivations, a single
qobject_cast is enough.
If the source type is polymorphic,
dynamic_cast is used. In other words,
dynamic_cast is used only for polymorphic source types (i.e. classes having at least one virtual function). In such classes, at compile-time we can't determine the most derived type of pointers which point to base classes having virtual methods, only at runtime we can determine them.
About dynamic casting
void*, it's allowed to cast to but not cast from.
In your case
void* doesn't have any RTTI, so neither
dynamic_cast can be used.