July 20, 2011

huckfinn huckfinn
Lab Rat
93 posts

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

 

Hello people,

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

  1. #pragma once
  2. #include <QtGui>
  3. #include <QString>
  4. #include <QHash>
  5. #include "DataItem.h"
  6.  
  7. class DataController
  8. {
  9. public:
  10.  DataController(void);
  11.  ~DataController(void);
  12.  int removeDataItem(qint32 key) const;
  13. protected:
  14.  QHash<qint32, DataItem> dynamicData;
  15. };

And my source

  1. #include <QHash>
  2. #include "DataController.h"
  3.  
  4. DataController::DataController(void)
  5. {
  6.  //
  7. }
  8.  
  9. int DataController::removeDataItem(qint32 key) const
  10. {
  11.  return this->dynamicData.remove( key ) ;
  12. }

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

5 replies

July 20, 2011

Vijay Bhaska Reddy Vijay Bhaska Reddy
Lab Rat
399 posts

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

July 20, 2011

Johan Solo Johan Solo
Ant Farmer
119 posts
Vijay Bhaska Reddy wrote:
Your removeDataItem() is const function, and its trying to remove/modify your class member variable. That may be the problem??

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.

 Signature 

Linux : you can find worse, but it’s more expensive.

July 20, 2011

huckfinn huckfinn
Lab Rat
93 posts

Yes, thats it.

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

July 20, 2011

Vijay Bhaska Reddy Vijay Bhaska Reddy
Lab Rat
399 posts

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

July 20, 2011

huckfinn huckfinn
Lab Rat
93 posts

Yes, thats exactly what I have done ;)

 
  ‹‹ Search in a subtree of QTreeWidget      Resize a QGraphicsItem into a QGraphicsScene ››

You must log in to post a reply. Not a member yet? Register here!