0

So I have this base class which creates a thread that calls a virtual method upon construction. It was designed this way because I just want other developers to override this method and not both the constructor and this method. So when I inherit this class I supposed that the method that was going to be called was the override. it didn't work. my code for the constructor is the next one

IOHandler::IOHandler(int refresh_rate)
{
    alarm_is_set = false;
    terminate_threads = false;
    init_complete = false;
    update_cycle_thread = std::thread (& IOHandler::update_cycle,
                                                        this,
                                                refresh_rate);
}

but when I create a child class f.e.

class childClass: public IOHandler
{
      void update_cycle(int refresh_rate) override;
}

the function that is called is IOHandler::update_cycle, not the override, is it possible to do what I want to do? regards

heczaco
  • 198
  • 1
  • 13
  • 1
    You should not call virtual functions from a C++ constructor. See http://stackoverflow.com/questions/962132/calling-virtual-functions-inside-constructors – vz0 Sep 05 '16 at 20:44
  • @vz0: There is nothing wrong with calling virtual functions from a C++ constructor. Just don't expect it to do something it's not going to do (that is, progress further up the inheritance hierarchy than has so far been constructed). I have no idea what those answers are talking about. Now, doing so in the instantiation of a thread object... that's different :) – Lightness Races in Orbit Sep 05 '16 at 20:46
  • 1
    doing anything to do with threads in the constructor is almost always a terrible idea. Construct your object, then call `start()` on it. If that's impossible, make a wrapper that owns the object and does exactly that. Otherwise the path of regret will be yours to explore. – Richard Hodges Sep 05 '16 at 20:51

1 Answers1

2

You should not call a virtual function from the constructor: the object has not been fully constructed and your overridden function won't be available to call from the base, yet. This is the reason why std::thread receives a function object as argument. The alternative is usually to call a start() method after thread construction.

vz0
  • 32,345
  • 7
  • 44
  • 77