Initialization list members not in correct order

Members of a class are initialized in the order in which they are declared, not the order in which they appear in the initialization list. For this reason, you should list them in the initialization list in the order in which they are declared in the class. This rule is based on Scott Meyer's Effective C++ and Bjarne Stroustrup's The C++ Programming Lanuage.

The CWARN.MEMBER.INIT.ORDER checker flags instances in which initialization-list members aren't in the order of declaration in your class.

Vulnerability and risk

This defect doesn't cause a vulnerability, but it's important for base class members to be initialized before derived class members, so they should appear at the beginning of the member initialization list. If class data members are used in the initializer, uninitialized usage could occur. This Klocwork warning allows you to re-order your initialization list in keeping with this rule of good practice.

Vulnerable code example

   #include <iostream>
   using namespace std;
   class C1{
     int v;
     C1(int v) { this->v = v; cout << "C1::C1: v is set to " << v << endl; }
   class C2{
    C2(const C1& c1) { cout << "C2::C2: c1.v == " << c1.v << endl; }
  class C{
    C2 c2;
    C1 c1;
    C() : c1(100), c2(c1) {}
  int main(){
    C c;
    return 0;

In this example, C::C() initialize lists c1 and c2 in wrong order. Although it looks like everything is correct, the compiler will initialize c2 first and then c1. So instead of having following intended output:

C1::C1: v is set to 100
C2::C2: c1.v == 100

the result is

C2::C2: c1.v = 32767
C1::C1: v is set to 100

External guidance