Can't Create a Thread in a Class?

Hello everyone, I have a class and inside it I have this function:

1
2
3
4
DWORD CALLBACK Function (void *)
	{
		return 0;
	}


Now when I try to create a thread with the CreateThread() function it says:

 
error: argument of type 'DWORD (nsCBPGUI::Testing::)(void*)' does not match 'DWORD (*)(void*)'|


How would I go about using a thread in a class? When ever I've tried to do this out side a class it has worked great.


Thanks.
You can't pass a class member function to CreateThread because a class member function needs to be called with a class pointer (so it can use this). You can either make the function static or a global function.
Yes, you need to create a thread with a function of the type LPTHREAD_START_ROUTINE as startaddress.
Then you can call the method of the object given as argument.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <Windows.h>
#include <iostream>

using namespace std;

class YOUR_CLASS
{
public:
      YOUR_CLASS( void );
      DWORD func( void );
};

DWORD __stdcall startMethodInThread( LPVOID arg )
{
       if(!arg)
            return 0;
       YOUR_CLASS *yc_ptr = (YOUR_CLASS*)arg;
       yc_ptr->func();
       return 1;
}

YOUR_CLASS::YOUR_CLASS( void )
{
      CreateThread(NULL, 4096, startMethodInThread, this, 0, NULL);
}

DWORD YOUR_CLASS::func( void )
{
      cout << "This is a new thread"  << endl;
}
Last edited on
Topic archived. No new replies allowed.