0

Suppose I have:

class Base
{
    public:

        void operator()()
        {
            this->run();
        }

        virtual void run () {}
}

class Derived : public Base
{
    public:

        virtual void run ()
        {
            // Will this be called when the boost::thread runs?
        }
}

int main()
{
    Base * b = new Derived();
    boost::thread t(*b); // <-- which "run()" function will be called - Base or Derived?
    t.join();
    delete b;
}

From my tests, I cannot get Derived::run() to be called. Am I doing something wrong, or is this impossible?

Dan Nissenbaum
  • 13,558
  • 21
  • 105
  • 181

2 Answers2

2

By passing *b you actually "slice" Derived object, i.e. pass Base instance by value. You should pass Derived functor by pointer (or smart-pointer), like this:

thread t(&Derived::operator(), b); // boost::bind is used here implicitly

Of course, pay attention to the b lifetime.

Igor R.
  • 14,716
  • 2
  • 49
  • 83
0

@GManNickG's comment is the cleanest answer, and works perfectly. Boost.Ref is the way to go.

thread t(boost::ref(*b));
Dan Nissenbaum
  • 13,558
  • 21
  • 105
  • 181