NOTE: I know there are many questions that talked about that but I’m still a beginner and I couldn’t understand the examples.
I got a function prototype that goes like this:
int someFunction(const char * sm);
Here, as you know, const char* means that this function can accept const or non-const pointer-to-char. I tried something like that in the function body:
someMemberVar = sm;
someMemberVar is just a pointer-to-char. The compiler gives me an error telling me:
cannot convert from const char* to char*.
Here, I didn’t pass a constant, so either sm or someMemberVar aren’t constants. So, what constant the compiler is talking about?
I’ll try to put in simpler terms what others are saying:
The function
someFunctiontakes a read-only string (for simplicity’s sake, thoughchar *could be used in umpteen other cases). Whether you pass in a readonly string tosomeFunctionor not, the parameter is treated as read-only by the code executing in the context of this function. Within this function therefore, the compiler will try to prevent you from writing to this string as much as possible. A non-const pointer is such an attempt to disregard the read-only tag to the string and the compiler, rightly and loudly informs you of such disregard for its type system 😉The first is a function which takes a readonly parameter. The second
constwritten after the closing parentheses is valid only for member functions. It not only takes a read-only parameter, but also gurantees to not alter the state of the object. This is typically referred to as design level const.