Search code examples
c++pointersappendconstantsqlist

appending pointers to class to a QList QList<Class* >


In my mainwindow.h I have a QList m_qlServoList which should store pointers to Servo objects:

QList<Servo* > m_qlServoList;

When I try to append a new Servo pointer to the QList:

m_qlServoList.append(new Servo(iID, iBaudRate));

The following Error results:

passing 'const QList<Servo*>' as 'this' argument of 'void QList<T>::append(const T&) [with T = Servo*]' discards qualifiers [-fpermissive]

The Servo class header looks as follows:

class Servo
{
public:
    Servo(const int &iID, const int &iBaudRate);
    ~Servo();

    void write_data(Data const& data) const;
    Data& receive_data() const;

private:
    Data m_oData;
};

It would be great if someone can explain me what I am doing wrong here. And how to correctly append pointers to Servo objects.


Solution

  • While we lack informations, it's likely that your QList<Servo *> is const.

    This could happen if your call was made from a const method of the class holding the QList.

    Lets see an example:

    class MyClass
        {
            private:
              QList<Servo *> m_qlServoList;
            public:
              void addServo(Servo *ptr) const /* Notice the const here */
                {
                  m_qlServoList.append(prt); 
                }
         };
    
    /* from main */
    MyClass c;
    c.addServo(new Servo(iID, iBaudRate));
    

    This code wouldn't compile, because the addServo() method is const, which means that m_qlServoList will be considered as a const QList<Servo *>.