Reputation: 105
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
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.
Upvotes: 5