When reading tutorials and code written in C++, I often stumble over the const
keyword.
I see that it is used like the following:
const
The difference between the two is that the first has type void(char)
and the second has type int()const
.
A function that has such a type with const
at the end can only be a member function of a class, and it means that the member function does not change the class value (which this
refers to) as seen from outside the class. The compiler will check that to a degree, and any straight write to a class member in a const member function results in a compile time error, and the function can straightly only call const member functions on itself (special directives exist so you can tell the compiler that a member write won't change the class' value as seen from outside. This is done by the mutable
keyword).
In the functions you presented, one had a parameter of type char const
. Such a parameter cannot be changed inside its function. It has no effect on the function's type though, and no effect to the callers of the function.
The first function example is more-or-less meaningless. More interesting one would be:
void myfunc( const char *x );
This tells the compiler that the contents of *x
won't be modified. That is, within myfunc()
you can't do something like:
strcpy(x, "foo");
The second example, on a C++ member function, means that the contents of the object won't be changed by the call.
So given:
class {
int x;
void myfunc() const;
}
someobj.myfunc()
is not allowed to modify anything like:
x = 3;