Search code examples
c++initialization-list

C++ initialization lists multiple initializations


C++

#include <stdio.h>

class a
{ 
    public: 
        int var1; 
        a(int var) 
        {
            var1 = var; 
            printf("set var1 to %d\n", var1);
        } 
}; 
class b: public a 
{ 
    public: 
        int var2; 
        b(int d) : var2(d++), a(var2++)
        {
            printf("d: %d, var2: %d, var1: %d\n", d, var2, var1);
        } 
}; 

int main()
{ 
    int a = 5;
    b obj1(a);  
    printf("%d\n", obj1.var1);
} 

Output:

set var1 to 0
d: 6, var2: 5, var1: 0
0
[Finished in 0.7s]

Why is a.var1 not set to 6 here?


Solution

  • Because C++ ignores the order in which you list the member initializations. The base-class ctor is always called before other members are initialized.*

    So I believe you're invoking undefined behaviour here; you're passing var2 as the ctor argument, but it's not yet initialized.


    * The compiler should warn you about this, if you allow it. For example, compiling your code with GCC with the -Wall flag gives the following message:

    test.cc: In constructor "b::b(int)":
    test.cc:16: error: "b::var2" will be initialized after
    test.cc:17: error:   base "a"
    test.cc:17: error:   when initialized here