Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constructor call or function-style cast in C++

Tags:

c++

If I have the following c++ code:

class foo{
public:
    explicit foo(int i){};
};
void f(const foo &o){
}

And then I call

f(foo(1));

Is foo(1) constructor call or function-style cast?

like image 884
Qiang Li Avatar asked Nov 27 '11 23:11

Qiang Li


People also ask

Is constructor called when casting?

A constructor for a class type is called whenever a new instance of that type is created. If a cast creates a new object of that class type then a constructor is called.

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 a function style cast in C++?

The C-style cast consists of the type you want in parentheses, followed by the expression you want to be converted into that type, e.g. `(double)getInt()`. The function style cast works only slightly different, by stating the target type followed by the source expression in parentheses, i.e. `double(getInt())`.


2 Answers

They are the same thing.

like image 115
Oliver Charlesworth Avatar answered Oct 05 '22 23:10

Oliver Charlesworth


It's a function-style cast that results in a constructor call, so both.

like image 42
Stuart Golodetz Avatar answered Oct 06 '22 00:10

Stuart Golodetz