Virtual Functions in Constructor and Descturctor

  1. What is the behavior of invoking virtual functions from constructors or destructors?
  2. 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Base {
public:
Base() { init(); }
virtual ~Base() { release(); }

virtual void init() {
std::cout << "Base::init()\n";
}

virtual void release() {
std::cout << "Base::release()\n";
}
};

class Derived : public Base {
public:
Derived() {}
~Derived() {}

virtual void init() override {
std::cout << "Derived::init()\n";
}

virtual void release() override {
std::cout << "Derived::release()\n";
}
};


int main() {
Base* b = new Derived;
delete b;
}
1
2
Base::init()
Base::release()

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

Author

Joe Chu

Posted on

2025-04-25

Updated on

2025-05-05

Licensed under

Comments