@oblivioncth said in Why does the const Object returned by QList::at() block access to instance methods?:
Hey, going above and beyond! Thanks again.
You're most welcome!
I'm not completely ignorant in the ways of C++ though, I'm not 100% certain, but fairly confident that:
Const 1) Ensures the returned value can't be modified,
Yep.
the use cases of which I'll admit I'm not really privy to.
Use case 1:
Allow the caller to read the data without creating a copy, AND
Make sure the data is read-only
If the returned reference is non-const, the caller will be able to directly modify the object's internal memory. This breaks encapsulation.
Use case 2: Allow the function to be called in another const function.
There's a const and a non-const version of QList::operator[](int):
T & operator[](int i)
const T & operator[](int i) const
Version #1 allows the caller to modify the QList element. However, it cannot be called in a const function -- it will cause the error in your original post. Thus, version #2 is required for use in const functions.
I know that its only really useful when dealing with user defined classes and returning by value reference (which is the case in your example) to prevent memory modification if desired.
(Acknowledging your typo)
Why would it be "only really useful when dealing with user defined classes"? Notice that QList::at() returns a const reference.
I do remember seeing something about this being somewhat obsolete in C++ 11 (or was it 17) and forward, though I'm not sure why.
Returning const references is defintiely not obsolete.
You might be remembering move semantics, which is said to make passing parameters by const-reference obsolete: https://stackoverflow.com/questions/10231349/are-the-days-of-passing-const-stdstring-as-a-parameter-over
Qt will not be making this change anytime soon though; this is too disruptive.
Const 2) The pointer argument "arg" in that class is for the type "const MyOtherClass", i.e. a pointer to a constant value (value cannot)
Yep, myfunc() cannot modify the MyOtherClass object. (In other words, it can only call const methods of the object)
Const 3) Marks the pointer "arg" itself as pointer, so that the pointer itself also cannot be modified)
Yep. This is not very useful IMHO, but it's part of the language.
Const 4) Thanks to you, I now understand this means that the function does not modify the object instance that the function is being called on/from (i.e. cannot manipulate member variables).
Great!
Next, start thinking about the difference between logical const-ness and physical const-ness: https://isocpp.org/wiki/faq/const-correctness#logical-vs-physical-state
Btw I do like a lot of the explanations on that site as they provide a lot of detail and examples, and I had never read the article for const.
Agreed