Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a const method take a non const reference?

Tags:

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?

like image 792
Peanojr Avatar asked Sep 10 '26 02:09

Peanojr


2 Answers

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.

like image 92
eerorika Avatar answered Sep 12 '26 23:09

eerorika


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.

like image 43
Tobias Ribizel Avatar answered Sep 13 '26 00:09

Tobias Ribizel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!