Search code examples
c++pointersfunction-pointerspointer-to-member

Pass a function pointer as an argument between classes


How can we pass a function pointer as an argument? For example, the function pointer myFunPtr is an argument when calling class A and I need this pointer to point to function funcB in class B

 #include <iostream>


typedef void(*myFunPtr)(void);

class A {
public:
    A(myFunPtr ptr);
    virtual ~A();
    myFunPtr funptr;
};

A::A(myFunPtr ptr){
    std::cout << "Constructor A \n";
    funptr = ptr;
}

A::~A(){}

 
///////////////
class B {
public:
    B();
    virtual ~B();
    void funcB();
};

B::B(){
    std::cout << "Constructor B \n";
    A *objA = new A(funcB);
}

B::~B(){}

void B::funcB(){
    std::cout << " call B::funcB \n";
}

///////////////

int main(){
     B *objB = new B();
     delete objB;
        
    return 0;
}

Solution

  • This is a function pointer type to a free function (not a class member function):

    typedef void(*myFunPtr)(void);
    

    This is a B member function pointer type:

    typedef void(B::*myFunPtr)(void);
    

    Demo

    Here's another Demo that will call a member function in a B. To do that, a pointer to a B and a pointer to a B member function is stored in A.