axe
axe

Reputation: 2371

C++ const member functions are modifying member variables

Today I found out that code like that works. That sounds really strange to me, because as far as I always knew you can't modify any of members from const member function. You actually can't do it directly, but you can call non-const member function. if you mark member function as const that means that this pointer passed to the function is pointing to const object, then how non-const member function is called in the example bellow?

#include <iostream>

class X
{
public:
    void foo() const
    {
        ptr->bar();
    }
    void bar() {}
private:
    X * ptr;
};

int main()
{
}

Upvotes: 13

Views: 5379

Answers (3)

UncleBens
UncleBens

Reputation: 41331

When you have a pointer member, then the pointer is const in a const method. You won't be allowed to change the address stored in the pointer. But you can change the pointee all you like.

It's the difference between

X* const cannot_change_pointer;  //this is how top-level const applies to pointers
const X* cannot_change_pointee;

What's even more interesting is that const on a method has no effect whatsoever on reference members for the same reason (a const method would only prevent you making a reference refer to something else which can't be done with a reference anyway).

Upvotes: 5

neuro
neuro

Reputation: 15180

That's seems perfectly OK. The call to foo does not modify the ptr member. Hence, the constness of foo is respected.

my 2 cents

Upvotes: 0

quant_dev
quant_dev

Reputation: 6231

Your member variable is not X, but pointer to X. As long as foo does not modify the pointer, it can be const.

Upvotes: 13

Related Questions