Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Any reason why function returning pointer shouldn't be const?

Tags:

c++

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?

like image 835
Gravity Avatar asked Dec 27 '22 17:12

Gravity


1 Answers

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)

like image 101
eran Avatar answered Jan 22 '23 09:01

eran