19

boost::bind is extremely handy in a number of situations. One of them is to dispatch/post a method call so that an io_service will make the call later, when it can.

In such situations, boost::bind behaves as one might candidly expect:

#include <boost/asio.hpp>
#include <boost/bind.hpp>

boost::asio::io_service ioService;

class A {
public:     A() {
                // ioService will call B, which is private, how?
                ioService.post(boost::bind(&A::B, this));
            } 
private:    void B() {}
};

void main()
{
    A::A();
    boost::asio::io_service::work work(ioService);
    ioService.run();
}

However, as far as I know boost creates a functor (a class with an operator()()) able to call the given method on the given object. Should that class have access to the private B? I guess not.

What am I missing here ?

Gabriel
  • 2,841
  • 4
  • 33
  • 43

2 Answers2

38

You can call any member function via a pointer-to-member-function, regardless of its accessibility. If the function is private, then only members and friends can create a pointer to it, but anything can use the pointer once created.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
8

Its through pointer-to-member-function, boost calls private functions. A member function of the class creates the pointer, and passes it to boost, and later on, boost uses that pointer to call the private function on an object of the class.

Here is one simple illustration of this basic idea:

class A;

typedef void (A::*pf)();

class A 
{
public:     
    pf get_ptr() { return &A::B; } //member function creates the pointer
private:    
    void B() { cout << "called private function" << endl; }
};

int main() {
        A a;
        pf f = a.get_ptr();
        (a.*f)();
        return 0;
}

Output:

called private function

Though it doesn't use boost, but the basic idea is exactly this.

Note that only member functions and friend can create pointer to private member function. Others cannot create it.

Demo at ideone : http://ideone.com/14eUh

Nawaz
  • 353,942
  • 115
  • 666
  • 851