Search code examples
c++constructorcallbackvirtualasynccallback

What happens when an asynchronous callback calls a virtual function, while base class constructor is not returned yet?


I have the following scenario:

class Caller{
public:
  Caller()               {...}
  void register(Base* b) {...}
  void callBase() { b->virt()}
};

class Base {
public:
  Base(Caller c)      { println("Base::Base()");  c.register(this); sleep(30); }
  virtual void virt() { println("Base::virt()"); }
};

class Derived : public Base {
public:
  Derived()           { println("Derived::Derived()"); }
  virtual void virt() { println("Derived::virt()"); }
};

I know normally if someone calls virt on the derived class Derived::virt() will be called. But here, if the function callBase is called while Base is sleeping in the parent constructor, which function will be called? Base::virt() or Derived::virt()?

Thanks


Solution

  • According to the C++ Lite FAQ 23.5, Base::virt() will be called.

    Anyway, it's really not something you want to do - if your object is used by another thread without proper initialization, you can encounter all sorts of nasty race conditions. For example, what would happen if the second thread called virt exactly when the vtable is set? Who's to guarantee that setting the vtable during object construction is an atomic operation?

    You should design your code in such a way that your objects aren't used before they're fully initialized.