Alex Rivera | Logout

C++ const member functions are modifying member variables

Asked 2011-09-12T15:40:32.293
14

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()
{
}
Edit
Report

1 Answer

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

answered 2011-09-12T15:44:37.820

Your Answer