Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between int x=1 and int x(1) in C++? [duplicate]

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.

like image 365
bobo Avatar asked Oct 03 '09 06:10

bobo


2 Answers

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.

like image 110
CB Bailey Avatar answered Nov 07 '22 05:11

CB Bailey


For POD-types, both statements are identical.

like image 33
mmx Avatar answered Nov 07 '22 04:11

mmx