Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Changed guideline ID to match section.

...

Consequently, the order in which constructor initializers appear is actually irrelevent, as the order in which they are executed is determined by external items, such as the order of the class fields. Reordering the initializers has no effect on the code execution, but can confuse programmers and lead to undefined behavior.

Non-Compliant Code Example

Code Block
bgColor#FFcccc
class C {
  int a;
  int b;
public:
  C() : b(3), a(b+1) {}
};

In class c's default constructor a is initialized before b because a is declared before b in the class body. Consequently a's initialization depends on the unitialized value of b, and so a will likely hold garbage.

Implementation Details

MSVC 2008 compiles this code without warning. It sets c.b to 3, and c.a to -858993459.

G++ 4.3.3 issues a warning regarding the misordered initializers. It sets c.b to 3 and c.a to 32515.

Non-Compliant Code Example

This code reorders the initializers correctly:

...

This code is still noncompliant, but now the error is obvious, a clearly depends on b despite being initialized first.

Compliant Solution

This code resolves the dependency.

...

Note that it is perfectly reasonable for initializers to depend on previously initialized values.

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ37-CPP

2 (medium)

2 (probable)

2 (medium)

P8

L2

References

Wiki Markup
\[[Lockheed Martin 05|AA. References#Lockheed Martin 05]\] AV Rule 75 Members of the initialization list shall be listed in the order in which they are declared in the class.
\[[ISO/IEC 14882-2003|AA. References#ISO/IEC 14882-2003]\] Section 12.6.2 "Initializing bases and members"

...