Virtual Functions in Constructor and Descturctor
- What is the behavior of invoking virtual functions from constructors or destructors?
- You should avoid invoking virtual functions from constructors or destructors.
1. Behavior
Invoking virtual functions from constructors and destructors will restrict the dynamic dispatch.
1 | class Base { |
1 | Base::init() |
The core reason C++ disables dynamic dispatch in constructors and destructors is safety—to avoid invoking virtual functions on an incompletely constructed or already partially destroyed object, which would lead to undefined behavior.
References
Virtual Functions in Constructor and Descturctor
http://chuzcjoe.github.io/cpp/cpp-virtual-function-in-constructor-and-destructor/