Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can boost::bind call private methods?

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 ?

like image 467
Gabriel Avatar asked Jun 30 '11 16:06

Gabriel


People also ask

What does boost :: bind do?

boost::bind is a generalization of the standard functions std::bind1st and std::bind2nd. It supports arbitrary function objects, functions, function pointers, and member function pointers, and is able to bind any argument to a specific value or route input arguments into arbitrary positions.

How do you call a private method outside the class in PHP?

If you instantiate the class Demo and you call $demo->myMethod(), you'll get a console: that console can access the first method writing a command like: > $this->myPublicMethod(); But you cannot run successfully the second one: > $this->myPrivateMethod();


2 Answers

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.

like image 179
Mike Seymour Avatar answered Oct 19 '22 16:10

Mike Seymour


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

like image 33
Nawaz Avatar answered Oct 19 '22 17:10

Nawaz