Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function-style cast vs. constructor

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?
like image 422
Basj Avatar asked Aug 04 '17 11:08

Basj


People also ask

What is 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); }

What is C style cast?

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.


2 Answers

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;
like image 76
Konrad Rudolph Avatar answered Oct 03 '22 05:10

Konrad Rudolph


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.

like image 24
eerorika Avatar answered Oct 03 '22 06:10

eerorika