13

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()
{
}
7
  • 3
    Where is the code that changes variables - your code does nothing Commented Sep 12, 2011 at 15:42
  • Oops! Sorry :) This is const pointer and I don't modify the pointer itself, I modify the object under this pointer. Thanks anyway., this was too long night for my tired brain :) Commented Sep 12, 2011 at 15:43
  • I can't see no const here ??? Commented Sep 12, 2011 at 15:43
  • I can repro this in VS2008. The implementation of foo() should in my understanding not compile because a const member calls a non-const member. I have modified the code to bar modifying a member, and call foo on a const instance of X, no error message. (/W4) Commented Sep 12, 2011 at 15:46
  • @peterchen: The compiler is correct. constness is not transitive in that context, that is the X* ptr; will be a Xconst ptr, not a X constconst ptr; Commented Sep 12, 2011 at 15:49

3 Answers 3

13

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

Sign up to request clarification or add additional context in comments.

Comments

5

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).

1 Comment

a const method would only prevent you making a reference refer to something else which can't be done with a reference anyway - Amazing observation!
0

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

1 Comment

The fact that bar just happens to do nothing is not significant here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.