Static function calling derived funtion

I have a question that is making loops in my mind.

I'm wrapping a Win32 thread in a class. The class needs:

- a public start() method called to create and launch the thread.
- a protected run() method, wich will be overloaded by task-specific derived classes.
- CreateThread needs a static function, so I have a private static method that calls run() using the pointer passed as the (void*) argument.

So:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Thread
{
public:
	// Constructor/Destructor
	Thread(void);
	virtual ~Thread(void);

	// Create and run thread
	void start(void);

protected:
	// Static wrapper for member function
	static DWORD WINAPI entryPoint(void* vpThis);

	// Main funtion of the thread
	virtual void run(void) = 0;
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// ... empty Constructor/Destructor

void Thread::start(void)
{
	CreateThread(0, 0, this->entryPoint, (void*) this, 0, 0);
}

/*static*/
DWORD WINAPI Thread::entryPoint(void *vpThis)
{
	Thread* pThis = static_cast<Thread*> (vpThis);
	pThis->run();

	return 0;
}

void Thread::run(void)
{
}


What I intended with this is that a derived class would only need to implement run(). Ex:

1
2
3
4
5
6
7
8
9
class ThreadA : public Thread
{
public:
	ThreadA(void) {};
	virtual ~ThreadA(void) {};

protected:
	virtual void run(void) {/*Do something*/}
};


BUT! When entryPoint calls run, I get a runtime error of access violation.
Does the object stay valid until Thread::entryPoint() returns? Does it go out of scope prematurely?
Thanks a lot, that was the problem.

Can't believe I thought so mouch about the virtual functions and derived classes and forgot about such a simple topic...
Topic archived. No new replies allowed.