Search code examples
c++c++11initializationlist-initializationnarrowing

Why does a narrowing conversion warning appear only in case of list initialization?


I have the following code:

class A
{
    public:
        A(const unsigned int val) : value(val) {}

        unsigned int value;
};

int main()
{
    int val = 42;
    A a(val);
    A b{val};       // <--- Warning in GCC, error in Microsoft Visual Studio 2015

    return 0;
}

Why does the narrowing conversion warning appear only in case of list initialization usage?


Solution

  • list initialization was introduced since C++11 with the feature prohibiting implicit narrowing conversions among built-in types. At the same time, the other two "old-style" (since C++98) initialization forms which use parentheses and equal-sign like

    int val = 42;
    A a(val);
    A a = val;
    

    don't change their behavior to accord with list initialization, because that could break plenty of legacy code bases.