I know that a const
object can't call a non-const
member function. It says so in the C++14 Standard (ISO/IEC 14882:2014) Section 9.3.2, Paragraph 3:
A cv-qualified member function can be called on an object-expression (5.2.5) only if the object-expression is as cv-qualified or less-cv-qualified than the member function.
Does this constraint make sense if the member function does not modify anything? Or if the member function modifies a mutable variable? For example:
class My_Class {
public:
mutable int value;
void function( int x ) const { value = x; } // Correct
//void function( int x ) { value = x; } // Not Correct
My_Class() : value(0) {}
};
int main(){
const My_Class obj;
obj.function( 1 );
return 0;
}
In this specific case, if the function is const
, the program is correct and the function can modify a variable of the const
object. If the function is not const
, the program is not correct. So in the end, I need to write const
to be able to modify something, which should be the opposite purpose of const
.
Does anyone know why this rule is designed this way?
const
objects are not meant to be changed. That's that.mutable
is just a cheat and is meant to be used on member variables which aren't really part of the internal state of the object (e.g. a mutex, which must be locked or unlocked regardless ofconst
). – DeiDei