sashang
sashang

Reputation: 12194

gcc: lack of warning about order of initialization in constructors

Should gcc to warn about the order of initialization of member variables a and b in class C? Basically object b is initialized and it's constructor invoked before object A. This means that b uses an uninitialized a.

#include <iostream>

using namespace std;

class A
{
    private:
        int x;
    public:
        A() : x(10) { cout << __func__ << endl; }
        friend class B;
};

class B
{
    public:
        B(const A& a) { cout << "B: a.x = " << a.x << endl; }
};

class C
{
    private:
        //Note that because b is declared before a it is initialized before a
        //which means b's constructor is executed before a.
        B b;
        A a;

    public:
        C() : b(a) { cout << __func__ << endl; }
};

int main(int argc, char* argv[])
{
    C c;
}

Output from gcc:

$ g++ -Wall -c ConsInit.cpp 
$ 

Upvotes: 2

Views: 1772

Answers (1)

Cubbi
Cubbi

Reputation: 47428

In order for this to be an order of initialization issue, you need to actually attempt to initialize the subobjects in the wrong order:

public:
    C() : a(), b(a) { cout << __func__ << endl; } 
          ^^^ this is attempted initialization out of order

as written, the only violation is binding a reference (the argument of B::B(const A&)) to an object (C::a) before its lifetime begins, and that's a very questionable violation, since taking a pointer to a would actually be legal, under $3.8[basic.life]/5 (and dereferencing it still before a's initialization would be UB)

Upvotes: 6

Related Questions