Search code examples
c++default-constructor

C++ calling the default constructor with parens vs without parens


Possible Duplicate:
different types of initialization in C++

Is there any difference at all between calling the base constructor like

Foo afoo;

vs

Foo afoo();

Solution

  • Yes: the first is a variable definition, the second is a function declaration. Now lets discuss the more interesting question of the difference between these two expressions:

    new Foo()
    new Foo
    

    Whether there is a difference depends on the type of Foo and its members!

    • if Foo has an explicit default constructor the two are identical
    • if there is no default constructor, there is potentially a difference! If there is any member which is an aggregate or a built-in type, it will be initialized in the first expresion but not in the second except all members which have default construct will be default constructed.

    Note that this also applies to members of classes. For variables you cannot use the form using parenthesis, i.e. to make sure the object is initialized you need to use

    Foo aFoo = Foo();
    

    If there is no explicit constructor taking an argument or you don't know (e.g. in template code).