Rahul Naik
Rahul Naik

Reputation: 105

Why are member function pointers not accessed properly by corresponding members?

Consider this code snippet.

class B {
public:
    void up() {
        std::cout << "up" << std::endl;
    }
    void down() {
        std::cout << "down" << std::endl;
    }
    void init( void(B::*someFunc)() , void(B::*otherFunc)() ) {
        m_execute = someFunc;
        B* newB = new B();
        m_b = newB;
        m_b->m_execute = otherFunc;
    }

    void find() {
        (this->*m_execute)();
        (m_b->*m_execute)();
    }
private:
    void(B::*m_execute)();
    B* m_b;
};

int main(){
    B* b = new B();
    b->init(&B::up,&B::down);
    b->find();
}

I have a class B. Its private members are a pointer to B i.e. m_b and a function pointer. In the init() function, private member function pointer is given up() and function pointer of private member m_b is given down() When I run the code, B::up() is executed twice instead of executing B::up() and then B::down().

Upvotes: 4

Views: 135

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726649

This happens because you apply one object's m_execute to another object.

Fix this by changing this line

(m_b->*m_execute)();
//     ^^^^^^^^^
// Points to your m_execute, not m_b's

to this:

(m_b->*m_b->m_execute)();

Better yet, add a member function to run your own execute, and call it from B::find:

void find() {
    run_my_execute();
    m_b->run_my_execute();
}
void run_my_execute() {
    (this->*m_execute)();
}

This would avoid the confusion on whose pointer should be applied to what object.

Demo.

Upvotes: 5

Related Questions