#include <iostream>
struct Foo
{
Foo(int d) : x(d) {}
int x;
};
int main()
{
double x = 3.14;
Foo f( int(x) );
std::cout << f.x << std::endl;
return 0;
}
When I compile this code I get the following error:
[Error] request for member 'x' in 'f', which is of non-class type 'Foo(int)'
Suppose that in int main
I remove int
in Foo f(int(x))
.
I mean if I write just like this:
Foo f(x);
the code compiled correctly and got the output as 3.
So what happens if we type cast the argument like Foo f(int(x)) to invoke the constructor?
Foo f(int(x));
It is not a type cast, it's a function declaration - function f
that takes an int
called x
and returns a Foo
.
The grammar allows a (theoretically unlimited) set of parentheses around an identifier in a declaration. It is the same as if you wrote
Foo f(int x);
or
Foo f( int (((x))) );
As you already figured out, you don't need to cast, as conversion between a double
and and int
is implicit. But if you really wanted, you could say static_cast<int>(x)
instead or
Foo f((int (x)));
// ^ ^
which makes it an expression instead of declaration.
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