[Solved] [Moved] Can QList<T*> take subclasses of T?



  • Hi, I am having problems understanding why this doesn't compile.

    I have 2 classes, A and B where B publicly inherits A.
    The pseudocode is:

    @
    function(const QList<A*>& list){ ... }

    QList<B*>* list = ...;
    function(*list);
    @

    Error:

    cannot convert parameter 1 from QList<T> to Aconst with T = B

    I'd appreciate any suggestions. Thanks!

    EDIT: please use @-tags for code highlighting, Gerolf



  • You confused in templates and classes.

    B is subclass A
    but QList<B*> is not subclass QList<A*>

    i.e you can:
    @QList<B*>* bList;
    QList<A*>* aList;
    ...
    A *a = bList->at(0);
    aList->append(a);@

    but you can't

    @QList<B*>* bList;
    QList<A*>* aList;
    ...
    aList = bList;@



  • See "C++ FAQ 21.3":http://www.parashift.com/c++-faq-lite/proper-inheritance.html#faq-21.3 for an explanation and 21.1/21.2 for the background.

    PS:
    I moved this to the C++ guru forum, as it's a general C++ question, but not specifically Qt related.



  • Thanks for your help. I guess I was confused because Java allows this in their generic programming with List<B extends A>. I'm new to Templates but I figured it would work under the Liskov Substitution Principle, since all Bs are As and it's just a pointer (so the size of the object doesn't matter).



  • You have that List<B extends A> in C++ too, you can put all A subclass types into the list, but if you have B extending A you cannot assign a List<B> to a variable of type List<A>. Both are different cases.

    What you've tried does not work in Java either, the following snippet yields an error:

    @
    public InheritanceTest() {
    ArrayList<String> sl = new ArrayList<String>();
    String x = "abc";
    sl.add(x);

    ArrayList&lt;Object&gt; ol = new ArrayList&lt;Object&gt;();
    Integer z = new Integer(1);
    ol.add(z);
    
    ol = sl;
    

    }

    // Error on the last line:
    // Type mismatch: cannot convert from ArrayList<String> to ArrayList<Object>
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.