A simple basic fundamental doubt !
Hi,
I was just trying to understand the concept behind qobject_cast and have landed in to some dilemma :confused:. I would be more than happy if some one could tell me the difference between the two representation of the same logic. I am here by trying to expand the q_object macro to see how it is using the meta object for dynamic identification of the object type.
Preconditions
----------------
I have a QObject subclass,
Code:
class QMyTestClass
: public QObject{
Q_OBJECT
public:
QMyTestClass(){}
int Get(){return 23;}
};
QMyTestClass *o
First
-----
Code:
//QMyTestClass
QMyTestClass* l = reinterpret_cast<QMyTestClass*>(0);
n = m.cast(myptr);
o = static_cast<QMyTestClass*> (n);
Second
---------
Code:
n = reinterpret_cast<QMyTestClass*>(0)->staticMetaObject.cast(myptr);
o = static_cast<QMyTestClass*>(n);
In the first scenario I am getting the cast as NULL (i.e. o = NULL) where as in the second case I am getting the same as the correct cast. Just wondering what's the difference.
Regards,
Subhransu
Re: A simple basic fundamental doubt !
The first one won't work. The point of this statement is to have a pointer to a class without actual object of this class. It's a terrible (or a very nice, depending on the point of view) hack to make the template mechanism cast the result to a proper class.
Re: A simple basic fundamental doubt !
First, staticMetaObject ist static, so just use QMyTestClass::staticMetaObject.
Also, no need to reinterpret_cast a 0. If you just write QMyTestClass* l=0, it is just as well. (Better actually, because casts are bad, as is widely known...)
Code:
n = QMyTestClass::staticMetaObject.cast(myptr); // better
Ok, to your issue:
* what is myptr?
* the cast function is basically an internal of qobject_cast. It returns 0 if the pointer is not of the needed QObject subtype. Your static_cast does nothing but adjust (after the typecheck) to that subtype.
* The two examples should do the same.
Please give us your complete example. (Are you sure myptr is the same before executing the two versions of that code?)
Re: A simple basic fundamental doubt !
Quote:
Originally Posted by
caduel
First, staticMetaObject ist static, so just use QMyTestClass::staticMetaObject.
What if you don't know the class name? That's the point of the whole statement.
Quote:
(Better actually, because casts are bad, as is widely known...)
Hmm... why so? Bad casts are bad, good casts are good. qobject_cast<>() is among the latter.
Quote:
Code:
n = QMyTestClass::staticMetaObject.cast(myptr); // better
Try making a template function that performs a cast based on the type passed to it. Or implement a series of functions for each and every QObject subclass (existing and future).
Quote:
* The two examples should do the same.
It's not that simple.
Re: A simple basic fundamental doubt !
Quote:
It's not that simple.
Could you elaborate on that, pleaase?