开发者

How to perform casting with multiple inheritance

My classes structure is like:

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

Now, I get a pointer to the object:

QObject* someObject = getMethodHelper();

Here, I am extremely sure that someObject is a type of MethodHelper. I somehow want to cast it to IMethodHelper. How should I go about it?

My current thoughts are like QObject -> MethodHelper -> IMethodHelper, like:

QObject* someObject = getMethodHelper();
MethodHelper* myHelper = qobject_cast<MethodHelper*>(someObject);
IMethodHelper*开发者_运维技巧 myIHelper = dynamic_cast<IMethodHelper*>(myHelper);

is there a potential flaw in my approach?


You could do it the way you present, but it isn't necessary. The Below should work fine.

IMethodHelper* myIHelper = dynamic_cast<IMethodHelper*>(someObject);


IMethodHelper * myIHelper = dynamic_cast<IMethodHelper *>(someObject);

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

5.2.7/8 snippet:

The run-time check logically executes as follows: — If, in the most derived object pointed (referred) to by v, v points (refers) to a public base class subobject of a T object, and if only one object of type T is derived from the sub-object pointed (referred) to by v, the result is a pointer (an lvalue referring) to that T object.


Just to complement the answers, there is also Q_INTERFACES and Q_DECLARE_INTERFACE that allow casting using qobject_cast instead of dynamic_cast. The documentation advertises them mostly for building 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 service interface com.example.IFileService/1.0?) And, of course, they work with RTTI turned off if you ever need to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜