C++ – Copy Initialization in Constructor Initializer

c++constructorinitialization

Why can't my constructor initializer use copy initialization?

struct S { int a; S(int b) : a(b)  {} }; // direct initialization compiles
struct T { int a; T(int b) : a = b {} }; // copy initialization does not

I am confused because a(b) and a = b are both expressions (postfix and assignent expressions, resp.), and my C++ book [1] says that "An initializer may be any arbitrarily complex expression."

[1] Lippman, Lajoie, Moo. "C++ Primer, 4th ed." p457.

Best Answer

That's not direct initialization. T a = b; is called copy intialization. Direct initialization is T a(1, 'foo', false);, and in your constructor you would write the familiar T(int b) : a(b, 'foo', false) { } to achieve this effect, as you already have in your first example.

By contrast, T a; is called default initialization, which you achieve by leaving a variable entirely unmentioned in the initializer list. Its effect is to call the default constructor on class types, and to perform no initialization at all on fundamental types (ditto for arrays).

By contrast again, value initialization can be written as T(int b) : a() { }. You can also use value-initialization in new expressions, but they're tricker in automatic declarations due to the vexing parse.

I think direct, default and value initialization are the only permissible forms of initialization in initializer lists in C++98/03, while C++11 adds various flavours of uniform initialization to the mix.

Related Question