Home     |     .Net Programming    |     cSharp Home    |     Sql Server Home    |     Javascript / Client Side Development     |     Ajax Programming

Ruby on Rails Development     |     Perl Programming     |     C Programming Language     |     C++ Programming     |     IT Jobs

Python Programming Language     |     Laptop Suggestions?    |     TCL Scripting     |     Fortran Programming     |     Scheme Programming Language


 
 
Cervo Technologies
The Right Source to Outsource

MS Dynamics CRM 3.0

C++ Programming

Virtual Member Function


Hi,

  I am using a class with operator() as threadfunc for Boost.Thread. I
have inheritance used with those class but it does not work, see the
example:

// Snippet on
#include <iostream>
#include <vector>
#include <boost/thread.hpp>

class Bird
{
public:
  virtual void operator()() {std::cout << "a bird" << std::endl;}
  virtual ~Bird() {}

};

class Swan : public Bird
{
public:
  virtual void operator()() {std::cout << "a swan" << std::endl;}

};

int main()
{
  Swan mySwan;
  Bird* myBird = &mySwan;

  Bird *b = &mySwan;
  boost::thread thrd(*b);
  thrd.join();

  return 0;

}

// Snippet off

  I would like to see "a swan" displayed, but I get "a bird"
instead... and for some reason I don't want to do that:
  boost::thread thrd(mySwan);

  As the member function is virtual, on call of operator () on the
object b (which is a swan) I should see Swan::operator() called, no?
What it it I don't understand here?

  Thanks and regards,

JD

On 25 May, 11:02, jean.daniel.mich@gmail.com wrote:

when you dereference b, what you get is the Bird part of mySwan
object.

try instead
boost::thread thrd(boost::bind(&Bird::operator(), b));

or if you have TR1
::boost::thread thrd(std::tr1::bind(&Bird::operator(), b));

Hi

jean.daniel.mich@gmail.com schreef:

>   I am using a class with operator() as threadfunc for Boost.Thread. I
> have inheritance used with those class but it does not work, see the
> example:

[includes, class Bird, class Swan snipped]

> int main()
> {
>   Swan mySwan;
>   Bird* myBird = &mySwan;

>   Bird *b = &mySwan;
>   boost::thread thrd(*b);

 From the boost documentation:

| class thread : private boost::noncopyable   // Exposition only
| {
|   public:
|    // construct/copy/destruct
|    thread();
|    explicit thread(const boost::function0<void>&);
|    ~thread();

and

| template<typename F> functionN(F f);
| Requires:        F is a function object Callable from this.
| Postconditions:  *this targets a copy of f if f is nonempty, or
|                  this->empty() if f is empty.

So effectively you create a boost::function0<Bird> object that _copies_
*b (slicing!). You then create a boost::thread object from that.

Avoid the copy by using an additional indirection, e.g. consider
boost::ref :

   boost::thread thrd( boost::ref(*b) );

Markus

Markus, dasjotre,

  Both you solutions work. Thanks a lot!

JD

Add to del.icio.us | Digg this | Stumble it | Powered by Megasolutions Inc