-3

I have simple class,

class Func
{
public:
    Func()
    {
        cout<<"Constructor"<<endl;
    }

    int operator()(int)
    {
        cout<<"Operator ()";
        return 0;
    }
};
  1. When I create it's object by giving parenthesis, Func f();, it prints nothing, it should print Constructor. But when I create object without parenthesis it prints Constructor which is expected. What is the different between these two?
  2. When I try to use operator() f(2) it gives me compilation error.

error C2660: 'f' : function does not take 1 arguments

Isn't it strange behaviour or I am missing something?

Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137
  • 3
    Because you declare `f` to be a *function* that takes no arguments and return a `Func` object. – Some programmer dude Feb 19 '15 at 04:39
  • 1
    [most vexing parse](http://stackoverflow.com/q/20529434/1708801) – Shafik Yaghmour Feb 19 '15 at 04:40
  • 1
    @ShafikYaghmour Don't think it qualifies as "most" vexing. That's IMO reserved for something like `Foo f(Bar(), Baz());` – T.C. Feb 19 '15 at 04:41
  • @T.C. I asked Scott about this and he said they are all the most vexing parse – Shafik Yaghmour Feb 19 '15 at 04:42
  • @ShafikYaghmour Scott Meyers? – Pranit Kothari Feb 19 '15 at 04:42
  • Anyway, the more typical MVP comes along due to disambiguation rules; you have two alternative parses and one is picked over the another. In `Func f();`, there's no second parse. `()` is not permitted as an initializer there, by the grammar. – T.C. Feb 19 '15 at 04:48
  • Expanding on TC's comment: the specification for initializer (as part of a declaration) is `( expression-list )`, and [syntax]/2 says that *X-list* means *one or more X's...*. This is covered by a different piece of grammar to expressions denoting temporary objects, which has `( expression-list opt )` . – M.M Feb 19 '15 at 04:58

2 Answers2

3

Func f();, it prints nothing, it should print Constructor

That is not true whatsoever.

Here is how you create a Func:

Func f;

When I try to use operator() f(2) it gives me compilation error. error C2660: 'f' : function does not take 1 arguments. Isn't it strange behaviour or I am missing something?

Yes, it's strange, but it's not unexpected. When you wrote Func f() you declared a function called f returning a Func. Everything you try to do with f after that is, naturally, broken.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

This is a bit interesting here.

Func f();

is a forward declaration for a function, which takes no argument and return Func type object.

Check the below code:

#include <iostream>
using namespace std;

class Func
{
public:
    int operator()(int)
    {
        return 0;
    }
};

int main ()
{
    Func f();
    f();
    return 0;
}

Func f ()
{
    cout << "My Func" << endl;
    Func * f = new Func;
    return *f;
}

It will output "My Func" on stdout.

T.C.
  • 133,968
  • 17
  • 288
  • 421
Abhishek Mittal
  • 356
  • 1
  • 16