Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why QObject needs to be the first in case of multiple inheritance

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?

like image 550
Ferenc Deak Avatar asked Feb 24 '15 12:02

Ferenc Deak


People also ask

Does QWidget inherit from QObject?

QWidget inherits QObject and QPaintDevice The QObject class is the base class of all Qt objects. QObject is the heart of the Qt object model providing support for signals, slots, and the meta object system. The QPaintDevice class is the base class of objects that can be painted on with QPainter.

Which is the base class of all Qt objects?

The QObject class is the base class of all Qt objects. More... Note: All functions in this class are reentrant.

What is Q_object macro?

QObject is the base class for all Qt classes, Q_OBJECT macro is used to enable meta-object features in classes and finally moc is a preprocessor that changes Q_OBJECT macro instances to C++ source code to enable meta object system mechanism in the class in which it is used.


1 Answers

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.

like image 95
vahancho Avatar answered Sep 17 '22 22:09

vahancho