I learned that in C++,
typedef foo* mytype;
(mytype) a // C-style cast
and
mytype(a) // function-style cast
do the same thing.
But I notice the function-style cast share the same syntax as a constructor. Aren't there ambiguous cases, where we don't know if it is a cast or a constructor?
char s [] = "Hello";
std::string s2 = std::string(s); // here it's a constructor but why wouldn't it be ...
std::string s3 = (std::string) s; // ... interpreted as a function-style cast?
Function style casts bring consistency to primitive and user defined types. This is very useful when defining templates. For example, take this very silly example: template<typename T, typename U> T silly_cast(U const &u) { return T(u); }
C-style casts can be used to convert any type into any other type, potentially with unsafe results (such as casting an integer into a pointer type). (<type>)<value> This example casts an int to a double for the purpose of avoiding truncation due to integer division: double result = (double)4/5; Popular pages.
Syntactically, it is always a cast. That cast may happen to call a constructor:
char s [] = "Hello";
// Function-style cast; internally calls std::basic_string<char>::basic_string(char const*, Allocator)
std::string s2 = std::string(s);
// C-style cast; internally calls std::basic_string<char>::basic_string(char const*, Allocator)
std::string s3 = (std::string) s;
Conversion is a form of initialization. When a type is implicitly convertible to another, a functional cast is a form of direct initialization. The compiler knows which types are convertible.
Whenever something is converted to a class type, either a converting constructor of the target type or a conversion operator of the source type is used. In your examples, both casts call the default constructor.
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