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

An employee asked about some code like this that originally had templates.

I deleted the templates, but the main question remains: why compile it 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 executes const, therefore, inside CX :: execute, this const pointer.

But I can call the non-const member function through a member function pointer.

Are member functions a pointer to a documented hole in the const -ness of the world?

What (supposedly obvious to others) problems did we miss?

+5
source share
5 answers

object X, const X. const (.. , const), .

, :

// ...
private:
    X object;
// ...

.

+7

const n execute() this . this a const T* T*. "" const, , , , , . object , , - . , F, -. , .

, CX const, : , , , , . const- const, .

:

class MyClass
{
public:
    /* ... */

    int* p;

    void f() const
    {
        // member p becomes: int* const p
        *p = 5;   // not changing p itself, only the thing it points to - allowed
        p = NULL; // changing content of p in const function - not allowed
    }
};
+7

object of class X . , const. , , .

, const . " ", ++.

+3

foo object, this.

object X&, CX X& const ( , const X&), non const.

+1

One useful way to think about this may be that your X object is not a member of CX at all.

0
source

All Articles