Wednesday, 15 February 2012

windows - C++ Polymorphism problems when casting from void * -



windows - C++ Polymorphism problems when casting from void * -

i have next 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() { homecoming 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(); homecoming 0; } class derivedclass : public baseclass { public: virtual int somestuff() { homecoming 2; }; }; int main() { baseclass base; base.start(); derivedclass derived; derived.start(); }

every instance creates thread using winapi , helper function startthread delegates phone call method threadloop of object created thread. problem threadloop calls other virtual method, polymorphism doesn't seem work if create derived class other implementation of virual method.

why? how can prepare this?

edit: updated code, thread doesn't started in constructor.

there several issues code, such you're creating , running thread while object beingness constructed. bad design.

a clean design encapsulate thread functionalities in abstract class called thread, , derive it, overriding run method, example:

class thread : public noncopyable { protected: handle m_hthread; unsigned long m_id; private: static unsigned long __stdcall start(void* args) { static_cast<thread*>(args)->run(); homecoming 0; } public: thread(); virtual ~thread(); virtual bool start() { if ( m_hthread != nullptr && isrunning(m_hthread) ) { throw std::logic_error("cannot start thread, running."); } m_hthread = ::createthread(null, 0, start, this, 0, &m_id); homecoming m_hthread != nullptr; } unsigned long get_id() const; virtual unsigned long wait(); protected: virtual void run() = 0; };

and derived it:

class worker : public thread { protected: virtual void run() override; };

and utilize as:

worker workerobject; workerobject.start(); //do other works here //maybe create few more threads; workerobject.wait(); //wait worker complete!

c++ windows multithreading inheritance polymorphism

No comments:

Post a Comment