c++ - pure virtual method called in thread of concrete class -


i have problem virtual methods in c++ on multithreading context (linux).

this next example points out problem:

class base {  };  class concrete1: public base {    //define pure virtual function     virtual void func() = 0; };   class concrete2: public concrete1 {     //override of virtual func     void func() {}      void run(){         //....         pthread_create(&handle, null, concrete2::thread, static_cast<void*>(this));     }      static void* thread(void arg*){         concrete2 *ptr = static_cast<concrete2*>(arg);         //concrete1 *ptr = static_cast<concrete2*>(arg);    // same error           while(1){             //....            ptr->func()         }     } };  int main(){   concrete2 obj;   obj.run();    pthread_exit(null);   return 0; } 

when line ptr->func() executed, following error appears:

pure virtual method called terminate called without active exception 

can tell me why pure virtual method being called instead of overrided method?

concrete2 created on stack , destroyed run called.

the spawned thread not keep obj alive.

your thread function trying dereference destroyed object, aka dangling pointer, constitutes undefined behavior.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -