Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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
ex1
ex1
OOP30-EX1: Since valid uses cases exist that involve calling (non-pure) virtual functions from the constructor of a class, it is recommended to explicitly qualify the name of the virtual function with the name of the class that defines it. This approach silences warnings from compilers such as HP aCC that diagnose violations of the rule. Note that calls to ordinary, non-virtual member functions that call virtual functions of the same class that aren't so qualified may be unsafe and thus lead to diagnostics. Thus, this exception does not extend to such cases.

Code Block
bgColor#ccccff
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.

...