C++ | Binding a Member Function

In this article, we saw how to bind a function with parameters and placeholders and some of its benefits. There we used a normal function. Here will see how to bind member function of a class.

Binding a Static Member Function

Binding a static member function is just like binding a normal function.

#include<iostream>
#include <functional>

class C {
public:
    static void func(int a, int b) {
        std::cout << (a - b) << std::endl;
    }
};


int main() {
    auto ob = std::bind(&C::func, 5, std::placeholders::_1);
    ob(3);

    return 0;
}

The func() is a static member function of the class C. We referred this function as “&C::func” in the std::bind() call. We bound the first parameter with 4 and the second parameter with a placeholder. The returned object is called in the next line with one parameter. The passed parameter to ob() will be used in place of the placeholder, i.e. second parameter.

We got the expected output.

$ g++ -o test test.cpp
$ ./test 
2

Binding a Non-Static Member Function

Like we can not call a non-static member function without an object, we can not bind an non-static function without an object also.

#include<iostream>
#include <functional>

class C {
public:
    void func(int a, int b) {
        std::cout << mem + (a - b) << std::endl;
    }

    int mem = 0;
};


int main() {
    C oc;
    
    oc.mem = 100;
    auto ob = std::bind(&C::func, oc, 5, std::placeholders::_1);
    
    oc.mem = 200;
    ob(3);

    return 0;
}

In the std::bind() function, we passed the member function as the first parameter and the corresponding object, oc, as the second parameter. The function is bound with respect to the object.

Another interesting thing to noticed here is that when we bound the function, the member variable, mem, had the value 100. Before we called the returned object, ob, the mem was set to 200. But the value 100 was used, when we called ob.

That means that when we are binding a member function of an object, the state of the object of that moment will be used when we will call the returned object.

The following output confirms that.

$ g++ -o test test.cpp
$ ./test
102

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
0
0