Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

foo_1(); in other words it's known as Null Intialize you must know difference between the object creation and value intialization.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top