Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with type casting the argument of the constructor

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

like image 568
user2416871 Avatar asked Jun 25 '13 14:06

user2416871


1 Answers

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.

like image 155
jrok Avatar answered Sep 21 '22 21:09

jrok