...
Because of this difference in behavior, it is recommended that you never invoke an object's virtual function while it is being constructed or destroyed.
Non-Compliant Code Example
Consider a design that attempts to seize and release an object's resources through calls to virtual functions from a base class's constructor and destructor.
...
The result of running this code is that no derived class resources will be seized or released during the initialization and destruction of the x object. At the time of the call to seize in the initialization of x, the D constructor has not been entered, and the behavior of the under-construction x object will be to invoke B::seize rather than D::seize. A similar situation occurs for the call to release in the base class destructor. If the functions seize and release were declared to be pure virtual functions, the result would be undefined behavior.
Compliant Solution
Avoid calling an object's virtual functions while it is being constructed or destroyed.
...
Note that it is perfectly legitimate to call virtual functions of other, fully constructed objects from a constructor or destructor.
Exceptions
| Anchor | ||||
|---|---|---|---|---|
|
| Code Block | ||
|---|---|---|
| ||
class A {
A() {
// f(); // WRONG!
A::f(); // okay
}
virtual void f();
};
|
Risk Assessment
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
OOP30-CPP | low | unlikely | medium | P2 | L3 |
Bibliography
| Wiki Markup |
|---|
\[[Dewhurst 03|AA. Bibliography#Dewhurst 04]\] Gotcha 75: Calling Virtual Functions in Constructors and Destructors \[[Sutter 04|AA. Bibliography#Sutter 04]\] Item 49: Avoid calling virtual functions in constructors and destructors. \[[Lockheed Martin 05|AA. Bibliography#Lockheed Martin 05]\] AV Rule 71.1 A class’s virtual functions shall not be invoked from its destructor or any of its constructors. |
...