Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading