Question on C++ Thread Class and inheritance/polymorphism with POSIX
Hello to everybody,
I cannot understand a strange behaviour of the following C++ code.
I'm on debian linux with gcc 4.1.2 and I'm using POSIX pthread.
I want to create a class which encapsulates the logic of threads in
order to have a simple Thread virtual class which must be INHERITABLE,
that means, I can create a thread with custom code simply inheriting
Thread class and overloading void run() method.
This is the code that I written:
int start();//method which allow user to launch the thread
virtual void run();virtual empty method run, the user will put
thread's code here
static void * gate(void *);//access point for pthread_create
pthread_t _tid;//thread ID
Thread::Thread() : _tid(0)
//create the thread
return pthread_create(&_tid, NULL,gate,this);
//wait for thread reconjunction
cerr << "hello, I'm the base thread" << endl;//debug print
void * Thread::gate(void * p)
//cast the void pointer
My intention is to inherit Thread and redefine Thread::run(), that is
for example :
class MyThread : public Thread
cerr << "hello, I'm the derived thread" << endl;//debug print
In the main funztion I put
I excpect to see "hello, I'm the derived thread" on the output,
instead I obtain is :
"hello, I'm the base thread"
I defined run as a virtual function so, even after a cast to void *
and then a cast to Thread * of the address of mt ( that is a MyThread
* ), I would excpect that the called method is decided not on the base
of the type of the pointer (Thread *) but on the type of the original
object (MyThread *) recorded in the v-table. This is the basics of the
The strange thing is that's happen only using threads. With the
following code instead everithing works correctly :
"hello, I'm the derived thread".
let me know what is the motivation of this strange behaviour.