I know a const method cannot modify the object from which it is called. Look at this code:
class A{
int a;
public:
void f(A & a_) const {
a_.a=5;
};
};
int main(){
A x;
x.f(x);
return 0;
}
Why does this code compile? Why can I even assign a reference to a non const object of the same class, when declaring the method as constant? In general how can the compiler check all the possible situations in which the function could modify the object?
Best Answer
This is an oversimplification, and slightly inaccurate.
A
const
function merely means that the implicitthis
pointer is a pointer toconst
.Because it is well-formed.
Because constness of the function does not affect what objects you can modify through a reference.
The compiler simply does not make such checks.