Storing a member function address address and assigning it to a Func pointer

15 views Asked by At
#include <functional>
#include <iostream>
#include <memory>

class BaseClass {
public:
    virtual bool memberFunction(int arg1, int arg2) {
        std::cout << "BaseClass::memberFunction(" << arg1 << ", " << arg2 << ")" << std::endl;
        return true;
    }
};

int main() {
    std::shared_ptr<BaseClass> basePtr = std::make_shared<BaseClass>();

    typedef bool(FunctionPointer*)(int a,int b);

    std::function<bool(int, int)> funcPtr = [basePtr](int arg1, int arg2) {
        return basePtr->memberFunction(arg1, arg2);
    };
    
    FunctionPointer = *(funcPtr.target<FunctionPointer>());

    return 0;
}

Even Though the above code compiles successfully, I get functionPointer as a null ptr (and hence the segfault) when I am looking into GDB. Any idea what could be the issue here? I was expecting FunctionPointer to have a valid address of memberFunction, so that I can use FunctionPointer to invoke member function from it.

0

There are 0 answers