I’m struggling to get my head around the differences between the various places you can put ‘const’ on a function declaration in c++.
What is the difference between const at the beginning:
const int MyClass::showName(string id){
...
}
And const at the end like:
int MyClass::showName(string id) const{
...
}
Also, what is the result of having const both at the beginning and at the end like this:
const int MyClass::showName(string id) const{
...
}
const int MyClass::showName(string id)returns aconst intobject. So the calling code can not change the returned int. If the calling code is likeconst int a = m.showName("id"); a = 10;then it will be marked as a compiler error. However, as noted by @David Heffernan below, since the integer is returned by copy the calling code is not obliged to useconst int. It can very well declareintas the return type and modify it. Since the object is returned by copy, it doesn’t make much sense to declare the return type asconst int.int MyClass::showName(string id) consttells that the methodshowNameis aconstmember function. A const member function is the one which does not modify any member variables of the class (unless they are marked asmutable). So if you have member variableint m_ain classMyClassand if you try to dom_a = 10;insideshowNameyou will get a compiler error.Third is the combination of the above two cases.