Hello,
I have some basic questions, I'm very interested in.
If I have a QMap<int,MyObject*>* and call method value on it, the method returns a pointer to a const instance of MyObject.
QMap<int,MyObject*>* myMap = new QMap<int,MyObject*>();
myMap->insert(1,new MyObject());
MyObject const * object_one = myMap->value(1); // const instance of myObject. I'm not allowed to call non-const methods on it.
object_one->changeMe(); //compiler will complain about it
QMap<int,MyObject*>* myMap = new QMap<int,MyObject*>();
myMap->insert(1,new MyObject());
MyObject const * object_one = myMap->value(1); // const instance of myObject. I'm not allowed to call non-const methods on it.
object_one->changeMe(); //compiler will complain about it
To copy to clipboard, switch view to plain text mode
but I can write it like this:
MyObject * object_one = myMap->value(1); // non-const instance of myObject. I'm allowed to call non-const methods on it.
object_one->changeMe(); //compiler wont't complain about it
MyObject * object_one = myMap->value(1); // non-const instance of myObject. I'm allowed to call non-const methods on it.
object_one->changeMe(); //compiler wont't complain about it
To copy to clipboard, switch view to plain text mode
And now I can mutate the instance. I want to know if this works just because of c-compatibility, if it's ok to use it like that (I would say no)?
Further I want to know how should I pass such an instance to another object which should hold the instance as mutable member (MyObject* myobject):
OtherClass(MyObject * myobject) : myobject(myobject){ }
MyObject const * const_object_one = myMap->value(1); // const instance of myObject. I'm not allowed to call non-const methods on it.
MyObject * object_one = myMap->value(1); // non-const instance of myObject. I'm allowed to call non-const methods on it.
OtherClass* other_object = new OtherClass(const_object_one);//fails
OtherClass* other_object = new OtherClass(object_one);//works
OtherClass(MyObject * myobject) : myobject(myobject){ }
MyObject const * const_object_one = myMap->value(1); // const instance of myObject. I'm not allowed to call non-const methods on it.
MyObject * object_one = myMap->value(1); // non-const instance of myObject. I'm allowed to call non-const methods on it.
OtherClass* other_object = new OtherClass(const_object_one);//fails
OtherClass* other_object = new OtherClass(object_one);//works
To copy to clipboard, switch view to plain text mode
Can I call the constructor passing the object via QMap::value, or should I use []->operator?
Thank you
Bookmarks