Capie
Capie

Reputation: 996

How to pass a member of class to another member of another class

I have a problem. I have two classes and I need to pass the member of one as a parameter to another member of the other class, like this:

class A{
public:
      int functionA(string x);
.
.
.};

And

class B{
public:
    void functionB( /*here would go functionA*/);
.
.
.
};

This is how functionB(...) would look.

void B::functionB( /*functionA*/){
string x = generateString();
functionA(x);
.
.
.
}

How could I do that? I tried with function<int(string)>& fun but looks like that is not intended when there are classes. I also tried functionB(int(aClass::*func)(string),aClass& a) but same result as before.

Any help would be appreciated.

Thanks!

Upvotes: 1

Views: 79

Answers (2)

Slava
Slava

Reputation: 44268

I tried with function& fun but looks like that is not intended when there are classes.

Looks like you tried wrong way, it works just fine:

class A {
public:
     void foo(std::string str) { std::cout << str << std::endl; }
};

int main()
{
     A a;
     std::function<void(std::string)> f = std::bind( &A::foo, &a, std::placeholders::_1 );
     f("test");
}

live example

Upvotes: 1

Chris Vig
Chris Vig

Reputation: 8802

If you're using C++11 or higher, you can do this with a lambda:

class A
{
public:
    void functionA(const std::string& x)
    {
        // do something with string
    }
};

class B
{
public:
    void functionB(const std::function<void(const std::string&)>& lambda)
    {
        lambda("test");
    }
};

And when you call it, you would do:

A a;
B b;
b.functionB([&a] (string x) { a.functionA(x); });

A complete demo is here: http://cpp.sh/5w6ng

Upvotes: 1

Related Questions