Why can I call a non-const member function pointer from a const method?

Posted by sdg on Stack Overflow See other posts from Stack Overflow or by sdg
Published on 2010-03-26T13:26:01Z Indexed on 2010/03/26 13:33 UTC
Read the original article Hit count: 244

Filed under:

A co-worker asked about some code like this that originally had templates in it.

I have removed the templates, but the core question remains: why does this compile OK?

#include <iostream>

class X
{
public:
     void foo() { std::cout << "Here\n"; }
};

typedef void (X::*XFUNC)() ;

class CX
{
public:
    explicit CX(X& t, XFUNC xF) : object(t), F(xF) {}      
    void execute() const { (object.*F)(); }
private:
    X& object;
    XFUNC F;
}; 

int main(int argc, char* argv[])
{   
    X x; 
    const CX cx(x,&X::foo);
    cx.execute();
    return 0;
}

Given that CX is a const object, and its member function execute is const, therefore inside CX::execute the this pointer is const.

But I am able to call a non-const member function through a member function pointer.

Are member function pointers a documented hole in the const-ness of the world?

What (presumably obvious to others) issue have we missed?

© Stack Overflow or respective owner

Related posts about c++