19.10.  Runtime Type Identification (RTTI)

[ fromfile: rtti.xml id: rtti ]

Abstract

This section covers dynamic_cast and typeid, two operators that enable runtime type identification (RTTI).

Example 19.20. src/rtti/dynamic_cast.cpp

[ . . . . ]
int processWidget(QWidget* wid) {
    
    if (wid->inherits("QAbstractSpinBox")) { 1
        QAbstractSpinBox* qasbp = 
            static_cast <QAbstractSpinBox*> (wid);
        qasbp->setAlignment(Qt::AlignHCenter);
    }
    else {
        QAbstractButton* buttonPtr = 
            dynamic_cast<QAbstractButton*>(wid);
        if (buttonPtr) {                     2
            buttonPtr->click();
            qDebug() << QString("I clicked on the %1 button:")
                .arg(buttonPtr->text());
        }
        return 1;
    }
    return 0;
}
[ . . . . ]
    QVector<QWidget*> widvect;

    widvect.append(new QPushButton("Ok"));
    widvect.append(new QCheckBox("Checked"));
    widvect.append(new QComboBox());
    widvect.append(new QMenuBar());
    widvect.append(new QCheckBox("With Fries"));
    widvect.append(new QPushButton("Nooo!!!!"));
    widvect.append(new QDateTimeEdit());
    widvect.append(new QDoubleSpinBox());
    foreach (QWidget* widpointer, widvect) {
        processWidget(widpointer);
    }
   return 0;
}

1

Only for QObjects processed by moc.

2

If non-null, it's a valid QAbstractButton.


[Note]Note

qobject_cast (Section 12.2) is faster than dynamic_cast but only works on QObject-derived types.

In terms of runtime cost, dynamic_cast is considerably more expensive, perhaps 10 to 50 times the cost of a static_cast. However, they are not interchangable operations and are used in different situations.