I wanted to know whether there's any reason a function returning a pointer shouldn't be const. I'm working on some code that seems to be const-correct in most places, but for some reason doesn't declare functions returning pointers as const. For example, it writes
virtual Joint* getJointByID(unsigned int id);
instead of
virtual Joint* getJointByID(unsigned int id) const;
If the getJointByID function itself in fact doesn't change any members of the class, is there any reason the const shouldn't be there?
This actually makes sense. If the function was to be declared with const
it means it could be used on a constant instance (constvar.getJointByID...). But if it returns a pointer to an internal structure that could then be modified, it will allow the user to bypass the instance's const limit.
When not declared with const
(like it is), you can't invoke the function on a const instance, and so the constness is preserved. If it had been declared const
, it should better have returned a const Joint*
.
(I'm assuming here that the Joint* is indeed part of the class data structure. If the class returns a newly allocated copy of some Joint
or so, it's ok for it not to be constant. This depends on the implementation)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With