0

I have a problem with virtual methods in C++ on a multithreading context (Linux).

This next example points out my 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 the line ptr->func() is executed, the following error appears:

pure virtual method called terminate called without an active exception

Can someone tell me why the pure virtual method is being called instead of the overrided method?

  • Where do you declare `func` as being virtual? – G.M. Apr 06 '17 at 10:22
  • @G.M. Doesn't matter, it is by virtue of being called the same, however the override keyword might help narrow it down if it is not. – Paul Apr 06 '17 at 10:24
  • I think related : https://stackoverflow.com/questions/7381757/c-terminate-called-without-an-active-exception – msc Apr 06 '17 at 10:25
  • What is `Concrete2`? – 1000ml Apr 06 '17 at 10:25
  • 2
    Please include how you're creating the objects and calling `run`. – Rotem Apr 06 '17 at 10:29
  • 1
    There is a lot missing from your code, for example construction and execution. Really, for this kind of questions, you need to provide a [Minimal Complete Verifiable Example](https://stackoverflow.com/help/mcve), otherwise all we can do is guessing. – Jan Hudec Apr 06 '17 at 10:31
  • 1
    What's `Concrete::thread` in the call to `pthread_create`? Please update your question to include an [mcve](http://stackoverflow.com/help/mcve). – G.M. Apr 06 '17 at 10:31
  • I updated the post again. Sorry for not providing mcve. The classes from my project are way more complex. This is just an example to show you where my code fails. – Paulo Félix Apr 06 '17 at 10:37

1 Answers1

0

Concrete2 is created on the stack and is destroyed as soon as run is called.

The spawned thread does not keep obj alive.

Your thread function is trying to dereference a destroyed object, aka a dangling pointer, which constitutes undefined behavior.

Rotem
  • 21,452
  • 6
  • 62
  • 109