Search code examples
c++inheritancelambda

Scheduling callback with virtual function in constructor


As Scott Meyers wisely taught us in Effective C++ (3rd ed.):

Item 9: Never call virtual functions during construction or destruction.

Now, consider the following piece of code:

class my_class
{

  my_class()
  {
    // here we _cannot_ call other_virtual()

    // but will this lambda call the correct function
    // if it is called after this CTOR has exited its scope?
    schedule_work([this]{ other_virtual(); });
  }

  void schedule_work(std::function<void()> callback);
  virtual void other_virtual() = 0;
}

class derived : public my_class
{
  derived() : my_class() {}
  
  // make sure to implement the pure virtual
  void other_virtual() override;
}

So is this reliable C++? Will this work according to the standard?


Solution

  • I was just curious whether there would be any compiler function call resolution that would make the wrong virtual function be called - pure or not.

    There is no virtual dispatch in the constructor. If you call other_virtual in the constructor of my_class, then my_class::other_virtual is called, no matter what the dynamic type of the object under construction actually is. Thats why Scott recommends to avoid calling virtual methods in a constructor in general, it works (unless the method is pure virtual), but it might surprise.

    Outside of the constructor (and outside of the destructor) there is virtual dispatch and if you call other_virtual on an object whose dynamic type is derived then derived::other_virtual will be called.