CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 1 of 1
  1. #1
    Join Date
    May 2000
    KY, USA

    Windows SDK Thread: How to use member functions as thread functions?

    Q: How to use member functions as thread functions?

    A: While trying to use member functions of a class as thread functions the compiler might complain with some kind of error like

    error C2664: 'CreateThread' : cannot convert parameter 3 from 'unsigned long (void *)' to 
    'unsigned long (__stdcall *)(void *)'
    None of the functions with this name in scope match the target type
    error C2665: 'AfxBeginThread' : none of the 2 overloads can convert parameter 1 from
    type 'unsigned int (void *)'
    The problem is that every thread function has its own prototype, which determines the parameters that gets passed from the operating system to it.

    In C++ every member function has a hidden parameter - the so-called 'this' pointer which will be automatically passed to the function. C++ is able to associate a function with a particular instance of an object by means of the 'this' pointer. Member functions access member variables through the 'this' pointer...

    class foo
      void func() { integer_ = 0; }
      int integer_;
    This code will be compiled as

    class foo
      void func(foo* this) {  this->integer_ = 0; }
      int integer_;
    The operating system does not call thread functions through objects therefore it cannot handle the automatically added 'this' pointer... To get member functions working as thread routines you need to tell the compiler explicitly not to expect a 'this' pointer. To avoid the automatic 'this' pointer you have two possibilities:

    • Non-member functions
    • Static member functions

    Non-member functions are not part of a class and therefore do not have a 'this' pointer. Static member functions do not receive a this' pointer either...thus, if you want to use a member function as a thread routine you need to declare it as 'static'...

    More information can be found here and here.

    Last edited by Andreas Masur; July 25th, 2005 at 12:41 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Click Here to Expand Forum to Full Width