Problems with QList and const Class

  • Hello, I have a problem when using QList<MyCLass*>::contains() and QList<MyClass*>::indexOf() with const instances.

    Here is my example code :

    @#ifndef MAINWINDOW_HPP
    #define MAINWINDOW_HPP

    #include <QList>
    #include <QMainWindow>

    #define ERROR -9

    class MyClass
    QString m_name;

        MyClass() :
            m_name("Default") {}


    class MainWindow : public QMainWindow

        QList<MyClass*> m_list;
        MainWindow() :
            m_list() {}
        int getIndexOf(const MyClass* myClass) const
            if (m_list.contains(myClass))
                return m_list.indexOf(myClass);
                return ERROR;


    #endif // MAINWINDOW_HPP

    When compiling, I have those errors:
    MainWindow.hpp:40: erreur : invalid conversion from 'const MyClass*' to 'MyClass*' [-fpermissive]
    qlist.h:886: error: initializing argument 1 of 'bool QList<T>::contains(const T&) const [with T = MyClass*]' [-fpermissive]
    MainWindow.hpp:42: erreur : invalid conversion from 'const MyClass*' to 'MyClass*' [-fpermissive]
    qlist.h:853: error: initializing argument 1 of 'int QList<T>::indexOf(const T&, int) const [with T = MyClass*]' [-fpermissive]

    I do not realy understand why because those methodes are expected constant template :
    QList::contains(const T&)
    and here, T = MyClass* and I send a const MyClass* in parameter.

  • There's a difference between a constant pointer to MyClass and a pointer to a constant MyClass. The getIndexOf Method has the latter kind as parameter, the QList methods expect the first kind.

    int a;
    the "const T&" of QList::contains guarantees, that a won't be changed.

    MyClass *a;
    guarantees, that a won't be changed. a, the pointer value (32/64-bit number). It's very different from const MyClass *a, which guarantees that *a, the object the 32/64-bit number points to, won't be changed.

    Solution: try const_cast, or change the list type to const MyClass*

    //EDIT: Something to think about along those lines:
    @int i;
    QList<const int> a;
    QList<const int*> b;
    a << i;
    b << &i;
    What will work, what will fail? Which list can/can't do what?

  • Ok,
    I understand the problem. Thanks for your help.

Log in to reply

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