Important: Please read the Qt Code of Conduct -

Casting QList<T> values to subclasses of T

  • Hello, I seem to have coded myself into a corner.

    Let's assume I have a class that publicly inherits QString called NewString

    Now if I do this

    @QList<QString> list;

    How do I get my NewString back out?

    @NewString string = list.value(0); // C2440: Cannot convert QString to NewString

    Casting does not work. It will work if I use QList<QString*> instead but I wanted to find a way to do this without pointers. I am using a QList to store a bunch of different implicitly shared objects that share the same base class but I am having difficulty restoring them after I pull them out of the QList.

    Any thoughts would be greatly appreciated! Thanks,

  • It doesn't work.

    What append does in your case is called slicing, i.e. it takes the QString sub-object of your NewString object. The QList never stores a NewString object in the first place.

  • What can work is a QList<QString*>
    But you lose all the advantages of implicit sharing.

    You might be better of writing a wrapper class instead of a derived class. Save the QString as one member of your class, and add any other information you want. Of course, it's not as convenient to use, but there's less danger of unintentional misuse, i.e. features that work because the QString subclass provides them, but that don't work right because your class should behave differently.

  • Thank you both. I think I'm just going to create a separate QList for each of my subclasses.

    The wrapper idea is interesting but I can't think of an elegant way to make it work for me. I'm implementing a component pattern to store mixed media playlists. So my QList would have ID3 tag info, Video info, and other QLists, all stored as implicitly shared data types (I used QString just to simplify the illustration).

    Anything, thanks for the help!

Log in to reply