5

This is a simple C++ constructor concept I'm having trouble with.

Given this code snippet:

#include <iostream>
using namespace std;

class Foo 
{
public:
    Foo ()      {       cout << "Foo()"  << endl;     }
    ~Foo ()     {       cout << "~Foo()" << endl;     }
};

int main()
{
    Foo f1;
    Foo f2();
}

The output was:

Foo()
~Foo()

It seems like Foo f2(); doesn't do anything. What is Foo f2(); And why doesn't it do anything?

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
Jason
  • 6,878
  • 5
  • 41
  • 55
  • possible duplicate of [Why is it an error to use an empty set of brackets to call a constructor with no arguments?](http://stackoverflow.com/questions/180172/why-is-it-an-error-to-use-an-empty-set-of-brackets-to-call-a-constructor-with-no) – Lightness Races in Orbit Dec 06 '11 at 07:22
  • IMO this is not a dupe. It's rather the question OP should have asked, but didn't know to. See here: http://meta.stackexchange.com/questions/109993/guidelines-for-closing-questions-as-exact-duplicate – John Dibling Dec 06 '11 at 17:01
  • @Jason: I'd be cautious with using the term *concepts* in the context of C++ if not talking about [this kind of stuff](http://en.wikipedia.org/wiki/Concepts_(C%2B%2B)). The title of your question is a bit confusing in that sense. – Andre Dec 06 '11 at 19:26

2 Answers2

9

Foo f2(); declares a function named f2 which takes no argument and returns an object of type Foo

Also consider a case when you also have a copy constructor inside Foo

Foo (const Foo& obj)     
{     
     cout << "Copy c-tor Foo()"  << endl;    
} 

If you try writing Foo obj(Foo()), in this case you are likely to expect a call to the copy c-tor which would not be correct.

In that case obj would be parsed as a function returning a Foo object and taking an argument of type pointer to function. This is also known as Most Vexing Parse.

As mentioned in one of the comments Foo obj((Foo())); would make the compiler parse it as an expression (i.e interpret it as an object) and not a function because of the extra ().

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • 3
    Might as well mention `Foo obj((Foo()))`, would make the compiler interpret it as an object rather than a function. – Alok Save Dec 06 '11 at 05:39
  • In simple terms, if parameter(s) are types, compiler would treat it as function prototype. Here `()` is actually `(void)`, where `void` is a type, and not an argument. – Ajay Dec 06 '11 at 20:04
4

You are actually declaring f2 as a function that takes no parameters and returns a Foo.

Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132