views:

252

answers:

3

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.

A: 

I'm no C++ expert, but if it gives the same result, does it matter? I guess if you were REALLY interested, you could compile (but not assemble) your code and have a look at what the difference is.

Edit: As has been mentioned elsewhere, they really are the same for builtin types.

Carl Norum
Of course it matters. You may see the same results, but that just might mean that you don't know what side-effects to look for or don't know about all the edge cases that would give you different results. This is a very reasonable questions from a beginner/intermediate programmer.
mobrule
+1  A: 

For POD-types, both statements are identical.

Mehrdad Afshari
+10  A: 

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.

Charles Bailey
And it's worth pointing out that Obj x; x = y; produces yet another variation. In this case, x will be default constructed. Then, at the next statement, the assignment operator will be called.
Daniel Yankowsky
Another thing worth noting is that allowing plain-old-data types such as int to be initialized this way (with a syntax analogous to invocation of a class constructor) allows templates to transparently work with both POD and class types.
Boojum
@Boojum: Adding that feature to the C++ language was meant to provide a single way of initializing objects of any type inside initialization lists. This is to me more important (and common) than initialization inside templates, that could be solved with the 'Type object = other_object' syntax.
David Rodríguez - dribeas