1

Possible Duplicates:
C++ cast syntax styles
What is the difference between (type)value and type(value) ?

In C++, when explicitly converting one built-in type to another, you can write:

int x = (int)c;
int x = int(c);
int d = (double)f;
int d = double(f);

I known that (T)v is a C-style cast, and I think the other syntax isn't technically a cast, but what is the other syntax called and what are its semantics? (And where to use which?)

Community
  • 1
  • 1
Martin Ba
  • 37,187
  • 33
  • 183
  • 337

1 Answers1

0

T(value) is actually an initialization of the type T, and because it's an initialization, an implicit type conversion can take place if the type of value and T are convertible. If T is a class-object, then one of it's constructors is called, either a default constructor that takes a single value and T and value are implicitly convertible types, or the copy constructor with the same condition that the two types are implicitly convertible. (T)value, as you've noted, is a C-style cast from the type of value, to the type T. Both in the end though are pretty much doing the same thing under the hood since if you did

T var1 = T(value);
T var2 = (T)value;

you'd get the exact same result, that is both create/return an object of type T which an be used to initialize an l-value of type T.

Jason
  • 31,834
  • 7
  • 59
  • 78