Uniform Initialization and default constructor arguments in C++11

1.8k views Asked by At

I am learning about new C++11 feature - uniform initialization. Wrote small program:

#include <iostream> 
using namespace std;

class C {
public:
    C(int a = 1, int b = 2) : a_{a}, b_{b}, n{0,1,2,3,4} {};
    int n[5];
    int a_,b_;

};

int main()
{
    C c = C{}; // should call C(int a = 1, int b = 2) with default arg.
    cout << c.a_ << "  " << c.b_ << endl;
    return 0;
}

However, I am getting unexpected result 0 0. In other words, everything is initialized to zero. The only way this could have happened: 1. Implicit default constructor was called, or 2. Initialization was not done correctly. (3. Compiler ???)

Why am I getting unexpected results ? Were there any changes to Constructor syntax that uses Uniform initialization in C++11 ?

EDIT: Using latest Intel Compiler:

1>------ Rebuild All started: Project: Unif_Init (Intel C++ 13.0), Configuration: Debug Win32 ------
1>  Source.cpp
1>  xilink: executing 'link'
1>  xilink: executing 'link'
1>  Unif_Init.vcxproj -> C:\Users\alex\documents\visual studio 2012\Projects\Unif_Init\Debug\Unif_Init.exe
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========
1

There are 1 answers

5
Jesse Good On BEST ANSWER

That's a bug in the compiler. C{} calls the default constructor to create a temporary which is used to copy-initialize the object c. C(int a = 1, int b = 2) is obviously a default one so it should use that. Does switching the initialization order to the order declared in the class help (probably not, but just a guess)? It seems the intel compiler isn't considering your ctor with default arguments as the default one.

C(int a = 1, int b = 2) : n{0,1,2,3,4}, a_{a}, b_{b} {};