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

1   #include <iostream>
2   using namespace std;
3   class C1{
4   public:
5     int v;
6     C1(int v) { this->v = v; cout << "C1::C1: v is set to " << v << endl; }
7   };
8   class C2{
9   public:
10    C2(const C1& c1) { cout << "C2::C2: c1.v == " << c1.v << endl; }
11  };
12  class C{
13    C2 c2;
14    C1 c1;
15  public:
16    C() : c1(100), c2(c1) {}
17  };
18  int main(){
19    C c;
20    return 0;
21  }

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