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 int x = 5;
I know that this means that x
is a constant variable and probably stored in read-only memory.
But what are
void myfunc( const char x );
and
int myfunc( ) const;
?
Best Answer
This means that the parameter
x
is a char whose value cannot be changed inside the function. For example:For the last one:
This is illegal unless it's inside a class declaration -
const
member functions prevent modification of any class member -const
nonmember functions cannot be used. in this case the definition would be something like:If you have specific class members that need to be modifiable in
const
member functions, you can declare themmutable
. An example would be a memberlock_guard
that makes the class'sconst
and non-const
member functions threadsafe, but must change during its own internal operation.