Start New Discussion within our Software Development Community
// 9-2. If we define the name function as a plain, nonconst member 
// function, what other functions in our system must change and why?

based on the question, the answer would be

// answer
bool compare(const Student_info&, const Student_info&);
// because this function uses the member function as it's parameter.
// giving writing access on a read-only variable is forbidden.

after removing the const on the type, the code doesn't compile and showed me these error which I assumed to be related with the standard library codes which may not allow const parameter on it's predicate function. No?

http://s17.postimg.org/gpok3bczj/ehem1.png

You're correct. The standard sort function will provide const objects to the comparison function. When calling a function with a const object as parameter, the function must take the object either by const-reference or by value. This is why changing the signature of the comparion function to non-const references does not work. And because you need non-const objects inside that function, the only remaining solution is to take those parameters by value. This is, of course, wasteful (useless copy), but that's one of the consequence of not caring to const-qualify things properly (i.e., making the "name" function non-const is stupid, leading to more stupid / wasteful code).

9-2. If we define the name function as a plain, nonconst member
function, what other functions in our system must change and why?

My answer to this question would be that every piece of code that depends on this function will have to change and code that relies on conventional constness rules will be broken, because making the "name" function non-const is a major breach of the integrity and consistency of the class' interface. I guess that's the lesson that this exercise is supposed to teach you.

This article has been dead for over six months. Start a new discussion instead.