3

I have the following case:

class A: public QObject

class B: public A, public QThread

Then the inheritance ambiguous happens because the QObject is inherited twice... Is there a solution to this?

vsoftco
  • 55,410
  • 12
  • 139
  • 252
Nyaruko
  • 4,329
  • 9
  • 54
  • 105
  • I have deleted my answer. `class A: public virtual QObject` does not solve your problem. – Gábor Angyal May 15 '15 at 19:01
  • 1
    Related: http://stackoverflow.com/q/2595849/3093378 It seems that `QThread` inherits non-virtually from `QObject`, so you are out of luck. – vsoftco May 15 '15 at 19:14

3 Answers3

5

QThread inherits non-virtually from QObject. Therefore, there is no way of inheriting down an hierarchy from both QThread and QObject without creating an ambiguity. Virtual inheritance won't help here, since you are not dealing with any diamond inheritance pattern.

A fix is to alter your design, as @Gabor Angyal mentioned.

Related question: how can i inherit from both QWidget and QThread?

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252
2

Multiple inheritance of QObject base classes does not work.

You can do something like this to solve this:

class A: public QObject

class B: public A
{
    Q_OBJECT
public:
    //...
    QThread *threadController() { return &mThreadController; }

private:
    //...
    QThread mThreadController;

}

You could also write delegates for the signals and slots you need instead of exposing the whole QThread object, or just write higher level API for class B and leave its internal QThread completely hidden. Depends on what you are trying to do, really.

If you really need to subclass QThread, then just use that as member variable type instead.

hyde
  • 60,639
  • 21
  • 115
  • 176
1

A little tricky, but might work for you:

template<class T>
class A: public T

class B: public A<QThread>

And if you need to use A just by itself then:

A<QObject> *a = new A<QObject>;

This pattern is called Mixin.

UPDATE

Ok, I realised that the moc system would obviously not work with this solution. I support hyde's answer instead.

Community
  • 1
  • 1
Gábor Angyal
  • 2,225
  • 17
  • 27
  • Won't work : http://stackoverflow.com/questions/4238204/is-it-possible-to-mix-template-derived-c-classes-with-qts-q-object – hyde May 15 '15 at 19:35