PDA

View Full Version : A simple basic fundamental doubt !



symsahoo
14th August 2008, 06:01
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,


class QMyTestClass : public QObject
{
Q_OBJECT
public:
QMyTestClass(){}
int Get(){return 23;}
};

QObject *n ;
QMyTestClass *o

First
-----

//QMyTestClass
QMyTestClass* l = reinterpret_cast<QMyTestClass*>(0);
const QMetaObject m = l->staticMetaObject;
n = m.cast(myptr);
o = static_cast<QMyTestClass*> (n);

Second
---------


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

wysota
14th August 2008, 06:59
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.

caduel
14th August 2008, 07:13
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...)


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?)

wysota
14th August 2008, 10:33
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.



(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.



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).


* The two examples should do the same.
It's not that simple.

caduel
14th August 2008, 10:46
It's not that simple.
Could you elaborate on that, pleaase?