I have a child class that starts a method of the base class as a thread. The child class has also implemented a pure virtual method from the base class. The thread then needs to call the child’s implemented version of the pure virtual method in the thread, but the thread throws an exception: “Pure virtual method called.” The code below demonstrates what happens on construction of a Child:
class Base {
std::thread messageThread;
virtual void processMessage(std::string msg) = 0;
static void checkForMessages(Base *c) {
while(true) {
std::string msg = "Hello";
c->processMessage(msg);
}
}
};
class Child : public Base {
Child() {
messageThread = std::thread(checkForMessages, this);
}
void processMessage(std::string msg) {
std::cout << "Message: " << msg << std::endl;
}
};
My understanding is that Child is still considered a Base until after the constructor finishes, so the thread is only able to see processMessage as a pure virtual function. I could implement checkForMessages for every child of Base, but that defeats the purpose of having the Base class in the first place.
How can I implement this correctly? Thank you for the help!
Edit: A complete example that demonstrates the issue, with an attempted fix: https://gist.github.com/4590476
Nothing stops the instance of
Derivedfrom being destroyed (or at least starting to be) before the thread runs. You need some smart pointers or some synchronization.