Possible Duplicate:
Is there a difference in C++ between copy initialization and assignment initialization?
I am new to C++, I seldom see people using this syntax to declare and initialize a variable:
int x(1);
I tried, the compiler did not complain and the output is the same as int x=1, are they actually the same thing?
Many thanks to you all.
Yes, for built in types int x = 1;
and int x(1);
are the same.
When constructing objects of class type then the two different initialization syntaxes are subtly different.
Obj x(y);
This is direct initialization and instructs the compiler to search for an unambiguous constructor that takes y
, or something that y
can be implicitly converted to, and uses this constructor to initialize x.
Obj x = y;
This is copy initialization and instructs the compiler to create a temporary Obj
by converting y
and uses Obj
's copy constructor to initalize x
.
Copy initalization is equivalent to direct initialization when the type of y
is the same as the type of x
.
For copy initalization, because the temporary used is the result of an implicit conversion, constructors marked explicit
are not considered. The copy constructor for the constructed type must be accessible but the copy itself may be eliminated by the compiler as an optmization.
For POD-types, both statements are identical.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With