I have the following code:
#include <windows.h>
#include <iostream>
static DWORD __stdcall startThread(void *);
class BaseClass {
private:
void threadLoop() {
// stuff ...
std::cout << someStuff() << std::endl;
// stuff ...
}
protected:
HANDLE handle;
virtual int someStuff() {
return 1;
}
public:
friend DWORD __stdcall startThread(void *);
BaseClass() {
handle = 0;
};
void start() {
handle = CreateThread(NULL, 0, startThread, this, 0, NULL);
}
~BaseClass() {
if(handle != 0) {
WaitForSingleObject(handle, INFINITE);
CloseHandle(handle);
}
}
// stuff
};
static DWORD __stdcall startThread(void *obj_) {
BaseClass *obj = static_cast<BaseClass *>(obj_);
obj->threadLoop();
return 0;
}
class DerivedClass : public BaseClass {
public:
virtual int someStuff() {
return 2;
};
};
int main() {
BaseClass base;
base.start();
DerivedClass derived;
derived.start();
}
Every instance creates a thread using the WINAPI and the helper function startThread
which delegates the call back to the method threadLoop
of the object which created the thread. Now the problem is that threadLoop
calls an other virtual method, but the polymorphism doesn't seem to work if I create a derived class with an other implementation of the virual method.
Why? How can I fix this?
Edit: I updated the code, so the thread doesn't get started in the constructor.
startThread()
?