4.3 KiB
[class.expl.init]
11 Classes [class]
11.9 Initialization [class.init]
11.9.2 Explicit initialization [class.expl.init]
An object of class type can be initialized with a parenthesizedexpression-list, where theexpression-list is construed as an argument list for a constructor that is called to initialize the object.
Alternatively, a singleassignment-expression can be specified as aninitializer using the= form of initialization.
Either direct-initialization semantics or copy-initialization semantics apply; see [dcl.init].
[Example 1: struct complex { complex(); complex(double); complex(double,double);};
complex sqrt(complex,complex);
complex a(1); // initialized by calling complex(double) with argument 1 complex b = a; // initialized as a copy of a complex c = complex(1,2); // initialized by calling complex(double,double) with arguments 1 and 2 complex d = sqrt(b,c); // initialized by calling sqrt(complex,complex) with d as its result object complex e; // initialized by calling complex() complex f = 3; // initialized by calling complex(double) with argument 3 complex g = { 1, 2 }; // initialized by calling complex(double, double) with arguments 1 and 2 â end example]
[Note 1:
Overloading of the assignment operator ([over.assign]) has no effect on initialization.
â end note]
An object of class type can also be initialized by abraced-init-list.
List-initialization semantics apply; see [dcl.init] and [dcl.init.list].
[Example 2: complex v[6] = { 1, complex(1,2), complex(), 2 };
Here,complex::complex(double) is called for the initialization ofv[0] andv[3],complex::complex(double, double) is called for the initialization ofv[1],complex::complex() is called for the initialization ofv[2],v[4], andv[5].
For another example,
struct X {int i; float f; complex c;} x = { 99, 88.8, 77.7 };
Here,x.i is initialized with 99,x.f is initialized with 88.8, andcomplex::complex(double) is called for the initialization ofx.c.
â end example]
[Note 2:
Braces can be elided in theinitializer-list for any aggregate, even if the aggregate has members of a class type with user-defined type conversions; see [dcl.init.aggr].
â end note]
[Note 3:
IfT is a class type with no default constructor, any initializing declaration of an object of typeT (or array thereof) is ill-formed if noinitializer is explicitly specified (see [class.init] and [dcl.init]).
â end note]
[Note 4:
The order in which objects with static or thread storage duration are initialized is described in [basic.start.dynamic] and [stmt.dcl].
â end note]