James Wilson
James Wilson

Reputation: 45

Function pointers with classes

I've been looking for a few days and at this point I assume that I'm not looking with the right criteria.Here's what I need to do

class AB
{
    public:
        std::function<void()>addr;
};

class BC
{
    public:
        void myTestFunc(std::string value)
        {
            std::cout << "AB::myTestFunc called: " << value << std::endl;
        }
};

int main(void)
{
    AB ob;
    BC obj2;

    ob.addr = std::bind(&obj2::myTestFunc, "");
    // so that i can call
    (ob.addr)("testing");

    return 0;
}

The problem is that I need to have a class that can allow instances of other classes its used to call a function on the "parent" or main class. The actual arguments and functions are obviously different but I cannot get it to work with a class public function. I cannot make it static as each instance of the "child" class will be calling a separate function. Please tell me what I should be searching for and / or what I'm doing wrong.

Upvotes: 0

Views: 72

Answers (1)

Stephen J
Stephen J

Reputation: 2397

I believe this is where you're going.

class AB
{
    public:
        std::function<void(std::string)>addr;
};

class BC
{
    public:
        void myTestFunc(std::string value)
        {
            std::cout << "AB::myTestFunc called: " << value << std::endl;
        }
};

int main(void)
{
    AB ob;
    BC ob2;
    std::string i = "testing";
    ob.addr = std::bind(&BC::myTestFunc, &ob2, i);
    ob.addr(i);

    return 0;
}

Upvotes: 1

Related Questions