Behaviour of QMetaObject within a base class constructor
I have a simple QObject-derived object:
class MyObject : public QObject {
Q_OBJECT
public:
MyObject(QObject* parent = 0);
};
MyObject::MyObject(QObject* parent) : QObject(parent) {
std::cout<<"[BASE] "<<this->metaObject()->className()<<std::endl;
}
And I further derive this object:
class MyDerivedObject : public MyObject {
Q_OBJECT
public:
MyDerivedObject(QObject* parent);
};
MyDerivedObject::MyDerivedObject(QObject* parent) : MyObject(parent) {
std::cout<<"[DERIVED] "<<this->metaObject()->className()<<std::endl;
}
Whenever I instantiate this class, I get the following output:
MyDerivedObject y;
## OUTPUT ###
[BASE] MyObject
[DERIVED] MyDerivedObject
I don't get it. Since the inheritance hierarchy is MyDerivedObject
-> MyObject
-> QObject, they both have the same instance of a QObject as a parent (right?). I know that most of the Run-time type information is provided via the moc, but that shouldn't change the fact that once I do a static_cast<QObject*>(/*MySomeObject*/)
on a pointer to one of those objects, they are the same thing (even in memory) as long as the QObject functionality is concerned. Then why do I get different return values of className()
? Either ways, how do I obtain the name of the开发者_如何学运维 type the QObject actually is of?
I am not sure about the details but each QObject-derived class has it own copy of meta object structure:
MyDerivedObject y;
qDebug() << (void*) y.metaObject();
qDebug() << (void*) y.MyObject::metaObject();
That gets you 2 different pointers to meta object.
Edit: I am not sure what your second question is. But if you want to know if a QObject is derived from a given class name, use QObject::inherits() to find out.
精彩评论