0

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;
}

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

7 Comments

It should be noted that in order to call a member function pointer, an instance of the class is needed to invoke the function on, e.g. B b; (b.*ptr)(); or B b; std::invoke(ptr, b, args...);
I will also note that this typedef syntax is now deprecated in preference for using, and that in this case you could also use a std::function<void()> if you need less coupling between the two types.
@DX-MON Sure, I kept the same syntax as OP had to make the diff clear. I have the using syntax in the demo with a note.
@Ted many thanks for the reply and the demo. Would it be possible to update the demo to call B::funcB? This is not called atm.
MohammedZiad I added a new demo. Note that I also added a pointer to a B in A like @MorningDewd mentioned.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.