5
#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?

Bart
  • 19,692
  • 7
  • 68
  • 77
user2416871
  • 543
  • 1
  • 4
  • 13

3 Answers3

4

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.

jrok
  • 54,456
  • 9
  • 109
  • 141
1

I don't get an error, I get a warning

C4930: 'Foo f(int)': prototyped function not called (was a variable definition intended?)

Try this instead:

Foo1 f1(int(pi));

and look up the most vexing parse, as suggested in the comments. You have declared a function, rather than called the constructor.

doctorlove
  • 18,872
  • 2
  • 46
  • 62
0

int(x) isn't how you properly cast. (int)(x) or (int)x will work for your particular case, I believe. Start with that and then let us know if you're still having problems.

Ricky Mutschlechner
  • 4,291
  • 2
  • 31
  • 36
  • 2
    Is it really incorrect? e.g. http://stackoverflow.com/questions/1594187/how-does-function-style-cast-syntax-work, http://stackoverflow.com/questions/4474933/what-exactly-is-or-was-the-purpose-of-c-function-style-casts, http://stackoverflow.com/questions/32168/c-cast-syntax-styles – doctorlove Jun 25 '13 at 14:52
  • 1
    `int(x)` casts `x` to type `int`. – Pete Becker Jun 25 '13 at 14:54
  • 1
    Perhaps avoiding c-style casts will make the problem go away. – doctorlove Jun 25 '13 at 14:58
  • I stand corrected. I didn't realize it was C-style - but I feel like it probably still shouldn't be done this way just to keep things simple. But at this point, that's just my opinion. – Ricky Mutschlechner Jun 25 '13 at 17:47