Peanojr
Peanojr

Reputation: 195

Why can a const method take a non const reference?

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?

Upvotes: 2

Views: 322

Answers (2)

eerorika
eerorika

Reputation: 238311

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.

Upvotes: 7

Tobias Ribizel
Tobias Ribizel

Reputation: 5421

A const member function cannot modify the object from which it is called using the "implicit" this parameter. f(...) is (ignoring member visibility) equivalent to the free function

void f(const A* this, A& _a) {
    _a.a = 5;
}

If you pass the same object as a non-const pointer or reference, you are still allowed to modify it.

Upvotes: 5

Related Questions