Search code examples
c++classconstructorinstancedefault-parameters

C++ Creating an instance of a class?


Possible Duplicate:
Default constructor with empty brackets
Instantiate class with or without parentheses?

Program:

class Foo
{
   public:
      Foo ( int bar = 1 )
      {
         cout << "bar=" << bar;
      }
};

int main() {

   cout << "0 - ";
   Foo foo_0 ( 0 ) ;
   cout << '\n';

   cout << "1 - ";
   Foo foo_1 ();
   cout << '\n';

   cout << "2 - ";
   Foo foo_4;
   cout << '\n';

   return 0;

}

Output:

0 - bar=0
1 - 
2 - bar=1

Question: why example #1 does not works, while examples #0 and #2 do?


Solution

  • Foo foo_1 ();
    

    is a function declaration, no object is created. It's a function called foo_1 that takes no parameters and returns a Foo object.

    The correct way to construct an object there is

    Foo foo1;
    

    This concept is called C++'s vexing parse. A short description is that anything that can be treated as a declaration, is.