<solved> C2662: 'function' : cannot convert 'this' pointer from 'type1' to 'type2'



  • Hello people,

    I have a QHash<quint32, DataItem> dynamicData which is not const!

    @
    #pragma once
    #include <QtGui>
    #include <QString>
    #include <QHash>
    #include "DataItem.h"

    class DataController
    {
    public:
    DataController(void);
    ~DataController(void);
    int removeDataItem(qint32 key) const;
    protected:
    QHash<qint32, DataItem> dynamicData;
    };
    @

    And my source
    @
    #include <QHash>
    #include "DataController.h"

    DataController::DataController(void)
    {
    //
    }

    int DataController::removeDataItem(qint32 key) const
    {
    return this->dynamicData.remove( key ) ;
    }
    @
    I get error C2662: 'QHash<Key,T>::remove' : cannot convert 'this' pointer from 'const QHash<Key,T>' to 'QHash<Key,T> &'
    My dynamicData is not constant, so remove should be callable.
    Whats the matter? I dont see the error..

    Cheers
    Huck



  • Your removeDataItem() is const function, and its trying to remove/modify your class member variable. That may be the problem??



  • [quote author="Vijay Bhaska Reddy" date="1311172988"]Your removeDataItem() is const function, and its trying to remove/modify your class member variable. That may be the problem??[/quote]

    It definitely is!

    A const method cannot modify the current instance (pointed by "this"). You have a conception problem in here : how could a method that removes an item from a container not modify the instance which "owns" the container...

    Of course there are workaround if you REALLY want the method to be const. You can either declare your QHash<qint32, DataItem> mutable or use const_cast to remove the "const" in front of the ‘const QHash<Key,T>’. I would'nt recommend this though.



  • Yes, thats it.

    No the method might be non const as well. I havent recognized that. Thankk you both!



  • My suggestion is .. I don't see a good reason why your removeDataItem() should be const. Remove const.



  • Yes, thats exactly what I have done ;)


Log in to reply
 

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