I work in a large collaboration (of mostly non-professional programmers, I being one of them). I regularly see examples of the following
void T::DoChanges(I i); // will make changes to internal structure of T (non-const)
V T::GetValue();
class A
{
private:
T* fMember;
public:
A();
T* GetMember() const {return fMember;}
}
, Where a use-case would be
A a;
I i;
a->GetMember()->DoChanges(i);
V v = a->GetMember()->GetValue();
This practice violates a tenant drilled into me when i took programming courses, i.e. that const refers not only to the bitwise structure of the class instance, but the internal logical structure. Under this philosophy, the member function should take the following forms:
T* GetMember() {return fMember;}
const T* GetMember() const {return fMember;}
I have heard that some people think that const should only refer to members, speaking strictly using the c++ terminology. How/why would someone argue for this type of practice?
So does it make sense to return a const pointer? It depends on what is const . If the constness refers to the pointed object, yes it does. If you try to make the pointer itself const, it doesn't make sense as it will be ignored.
If the function is non-constant, then the function is allowed to change values of the object on which it is being called. So the compiler doesn't allow to create this chance and prevent you to call a non-constant function on a constant object, as constant object means you cannot change anything of it anymore.
If the thing you are returning by reference is logically part of your this object, independent of whether it is physically embedded within your this object, then a const method needs to return by const reference or by value, but not by non-const reference.
const member functions may be invoked for const and non-const objects. non-const member functions can only be invoked for non-const objects. If a non-const member function is invoked on a const object, it is a compiler error.
Making the member function gives the indication to the users of this function that it will not modify any class members.
The returned member may or maynot be const
but making the member function const gives the users of the class a clear indication of the behavior of function.
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