Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt interfaces or abstract classes and qobject_cast()

Tags:

I have a fairly complex set of C++ classes that are re-written from Java. So each class has a single inherited class, and then it also implements one or more abstract classes (or interfaces).

Is it possible to use qobject_cast() to convert from a class to one of the interfaces? If I derive all interfaces from QObject, I get an error due to ambiguous QObject references. If however, I only have the base class inherited from QObject, I can't use qobject_cast() because that operates with QObjects.

I'd like to be able to throw around classes between plugins and DLLs referred to by their interfaces.

like image 788
Timothy Baldridge Avatar asked Sep 16 '10 12:09

Timothy Baldridge


People also ask

When to use interface vs abstract class?

An abstract class is used if you want to provide a common, implemented functionality among all the implementations of the component. Abstract classes will allow you to partially implement your class, whereas interfaces would have no implementation for any members whatsoever.

What is abstract class in c#?

Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the derived class (inherited from).

How do I create an abstract class in Qt?

You create an abstract class by declaring at least one pure virtual member function. That's a virtual function declared by using the pure specifier ( = 0 ) syntax. Classes derived from the abstract class must implement the pure virtual function or they, too, are abstract classes. // deriv_AbstractClasses.


1 Answers

After some research and reading the qobject_cast documentation, I found this:

qobject_cast() can also be used in conjunction with interfaces; see the Plug & Paint example for details.

Here is the link to the example: Plug & Paint.

After digging up the interfaces header in the example, I found the Q_DECLARE_INTERFACE macro that should let you do what you want.

First, do not inherit QObject from your interfaces. For every interface you have, use the Q_DECLARE_INTERFACE declaration like this:

class YourInterface { public:     virtual void someAbstractMethod() = 0; };  Q_DECLARE_INTERFACE(YourInterface, "Timothy.YourInterface/1.0") 

Then in your class definition, use the Q_INTERFACES macro, like this:

class YourClass: public QObject, public YourInterface, public OtherInterface {     Q_OBJECT     Q_INTERFACES(YourInterface OtherInterface)  public:     YourClass();      //... }; 

After all this trouble, the following code works:

YourClass *c = new YourClass(); YourInterface *i = qobject_cast<YourInterface*>(c); if (i != NULL) {     // Yes, c inherits YourInterface } 
like image 139
Venemo Avatar answered Sep 30 '22 00:09

Venemo