[Qt-interest] Sanity check on using dynamic_cast<> with Qt
Oliver.Knoll at comit.ch
Oliver.Knoll at comit.ch
Tue May 11 14:56:10 CEST 2010
K. Frank wrote on Tuesday, May 11, 2010 3:39 AM:
> ...
> [qobject_cast] doesn't require RTTI support and it works across
> dynamic library boundaries.
>
> Am I correct, therefore, that qobject_cast should be more portable
> than dynamic_cast across the platforms on which Qt runs?
It is more portable in a way, yes: dynamic_cast<> requires "RTTI" (Run-Time Type Information) be enabled in the compiler, which also produces slightly larger object code. In the early days not every compiler which was supported by Qt did support RTTI properly (and there is also a slight performance overhead).
So if you wish to:
- avoid using RTTI (for whatever reasons) OR
- query the type of an object created in another library (address space)
then qobject_cast is the way to go, because it simply evaluates the "Qt meta information" (http://doc.trolltech.com/4.6/metaobjects.html) which is there anyway - given that an object inherits from QObject AND contains the Q_OBJECT macro (which at the same time also dictates the restriction: it naturally only works with QObject based classes).
The later requirement - the class declaration *must* contain the Q_OBJECT macro (even if it does not add signals or slots of its own)! - can't be stressed enough! Otherwise the result is "undefined" (in practise you probably get the information from the last parent object which contains the Q_OBJECT macro)! Take a careful note of the warning in http://doc.qt.nokia.com/4.6/qobject.html#qobject_cast. ;) (1)
Because it is the Q_OBJECT macro which adds the required "class meta information" to the object in question (among other things) in the moc-step.
Cheers, Oliver
(1) Oh and yes, I AM talking with (bad) experience here ;)
--
Oliver Knoll
Dipl. Informatik-Ing. ETH
COMIT AG - ++41 79 520 95 22
More information about the Qt-interest-old
mailing list