0
Foo x(Bar());

I can write in inside another function and it compiles. Why? Also how a function declaration can get a temporary object in it's signature?

melpomene
  • 84,125
  • 8
  • 85
  • 148
TheLogicGuy
  • 682
  • 8
  • 19

1 Answers1

3

Well, you can do this:

Foo x();

This declares a function x that takes no arguments and returns Foo.

We can add parameters:

Foo x(int y, char z);

A parameter is just a variable declaration (x and z here).

We can omit the parameter names in a function declaration:

Foo x(int, char);

And we can declare a parameter as a function:

Foo x(Bar y());

Here we declare x as a function taking another function y (that takes no arguments and returns Bar) returning Foo.

Finally we can omit the parameter name here, too:

Foo x(Bar ());  // a function taking a function

That's how the syntax works.

Semantically, you might object, this is invalid because functions aren't value types. You can't copy a function, so you can't pass it by value. Which is true, but there's a rule that says any parameter declared as a function is silently adjusted to be a pointer by the compiler:

Foo x(Bar y());
// really means:
Foo x(Bar (*y)());

x takes a pointer to a function (taking no arguments and returning Bar).

Or without parameter names:

Foo x(Bar ());
// same as:
Foo x(Bar (*)());

This is similar to the rule that turns a parameter declared as an array into a pointer:

Foo x(Bar [42]);
// same as:
Foo x(Bar *);
melpomene
  • 84,125
  • 8
  • 85
  • 148
  • Why can I declare in inside another function and not only in the global scope? but when I want to add a body to the function I get an error – TheLogicGuy Nov 25 '17 at 10:13