heczaco heczaco - 1 year ago 173
C++ Question

Override thread functions c++

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,

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

vz0 vz0
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download