C++ – Why Can a const Method Take a Non-const Reference?

c++

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

I know a const method cannot modify the object from which it is called.

This is an oversimplification, and slightly inaccurate.

A const function merely means that the implicit this pointer is a pointer to const.

Why does this code compile?

Because it is well-formed.

Why can I even assign a reference to a non const object of the same class, when declaring the method as constant?

Because constness of the function does not affect what objects you can modify through a reference.

In general how can the compiler check all the possible situations in which the function could modify the object?

The compiler simply does not make such checks.

Related Question