How to cast with multiple inheritance

My class structure is similar:

class MethodHelper : public QObject, public IMethodHelper { public: // Stuff }; 

Now I get a pointer to the object:

 QObject* someObject = getMethodHelper(); 

Here I am very sure that someObject is a MethodHelper type. I somehow want to drop it in IMethodHelper. How can I do it?

My current thoughts are similar to QObject -> MethodHelper -> IMethodHelper , for example:

 QObject* someObject = getMethodHelper(); MethodHelper* myHelper = qobject_cast<MethodHelper*>(someObject); IMethodHelper* myIHelper = dynamic_cast<IMethodHelper*>(myHelper); 

is there a potential flaw in my approach?

+4
source share
3 answers

You can do it the way you imagine, but it is not necessary. The bottom should work fine.

 IMethodHelper* myIHelper = dynamic_cast<IMethodHelper*>(someObject); 
+7
source
 IMethodHelper * myIHelper = dynamic_cast<IMethodHelper *>(someObject); 

Cross throws are legal with dynamic_cast - if your types are polymorphic.

5.2.7 / 8 fragment:

A run-time check is performed as follows: - If in the most derived object referenced by (v), v points to (refers to) a public base class as a subobject of T, and if only one object of type T is obtained from a sub-object, which points to (refers to) by v, the result is a pointer (an lvalue) to this T.

+4
source

To complement the answers, there are also Q_INTERFACES and Q_DECLARE_INTERFACE , which allow casting using qobject_cast instead of dynamic_cast . The documentation advertises them mainly for creating plugins, but they can be used in any kind of project.

They are especially useful when creating "services." (As in, does this class implement the com.example.IFileService/1.0 service interface?) And, of course, they work with RTTI disabled if you ever need to.

+2
source

All Articles