Reputation: 856
I want to update my code from old style casting to new style one. I have some problems with understanding the different type of casts.
1 case
if (((QDataItem*)(*it))->GetType()==QDataItem::AudioTrack){
Here I have a class "QDataItem". This contain an enum of track types, like AudioTrack. Basing on a QTreeWidget I iterate through the QTreeWidget items. Each Item represents a QDataItem. Now with new casting I want to do:
if ((static_cast<QDataItem*>(*it))->GetType()==QDataItem::AudioTrack){
Is this there right way to do?
2 case In old style I have a twice casting
QAudioTrackItem *audio_track = (QAudioTrackItem*)(QDataItem*)(*it);
QAudioTrackItem is like QDataItem a class. I want to do here:
QAudioTrackItem *audio_track = reinterpret_cast<QAudioTrackItem*>(*it)
But I am not sure that this is correct in case of the missing QDataItem cast.
Is my result ok or do I have a bug?
Upvotes: 0
Views: 160
Reputation: 136
Is this there right way to do?
Yes, (QDataItem*)(*it)
and static_cast<QDataItem*>(*it)
should be identical with your code.
But if your classes have such inheritance structure:
class QDataItem : QObject {};
class QAudioTrackItem : QDataItem {};
you should really consider using qobject_cast<>() instead:
if (auto item = qobject_cast<QAudioTrackItem *>(*it)) {
....
}
Is my result ok or do I have a bug?
Maybe, it depends on how your inheritance structure look like.
If they inherit just like my example above, it's totally OK to use reinterpret_cast<>()
to convert any pointers between QObject
, QDataItem
and QAudioTrackItem
.
But if your classes have multiple inheritance:
class QDataItem {};
class QAudioTrackItem : QObject, QDataItem {};
reinterpret_cast
could kick your ass badly:
auto item = new QAudioTrackItem;
auto p1 = reinterpret_cast<QObject *>(item); // OK
auto p2 = reinterpret_cast<QAudioTrackItem *>(p1); // OK
auto p3 = reinterpret_cast<QDataItem *>(item); // Undefined Behavior
auto p4 = reinterpret_cast<QDataItem *>(p1); // Undefined Behavior
Upvotes: 1