6

According to http://qt-project.org/doc/qt-4.8/moc.html#multiple-inheritance-requires-qobject-to-be-first the QObject must be the first in the base classes when using multiple inheritance.

Is this because of some limitation in the moc tool or C++ memory layout problems are taken into consideration too, thus this restriction came into existence?

Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167

1 Answers1

5

Assume that we have a class Test declared as:

class Test : public Foo, public QObject
{
    Q_OBJECT
    [..]
};

If you take a look at the moc_test.cpp file that the moc tool has generated, you will see something like:

[..]
const QMetaObject Command::staticMetaObject = {
    { &Foo::staticMetaObject, qt_meta_stringdata_Command,
      qt_meta_data_Command, &staticMetaObjectExtraData }
};
[..]

Compiler will complain about staticMetaObject not being the member of Foo, as Foo is not a QObject. For some reason the moc tool generates this code taking the first parent class. Thus if you declare Test as:

class Test : public QObject, public Foo {};

The generated code will look fine to compiler.

I think this is made just for convenience because moc tool will hardly know which of the parent classes is a QObject without parsing the whole hierarchy.

Note: If you don't use the Q_OBJECT macro, you can derive your class from others in any order.

vahancho
  • 20,808
  • 3
  • 47
  • 55
  • 1
    I think it is not only the convenience, as within the derived class object the pointer to base classes will be at different positions (will have different offset). And I think that qt does some stupid casts. – BЈовић Feb 24 '15 at 13:10