Is there any good reason that an empty set of round brackets (parentheses) isn't valid for calling the default constructor in C++?
MyObject object; // ok - default ctor
MyObject object(blah); // ok
MyObject object(); // error
I seem to type "()" automatically everytime. Is there a good reason this isn't allowed?
Most vexing parse
This is related to what is known as "C++'s most vexing parse". Basically, anything that can be interpreted by the compiler as a function declaration will be interpreted as a function declaration.
Another instance of the same problem:
v
is interpreted as a declaration of function with 2 parameters.The workaround is to add another pair of parentheses:
Or, if you have C++11 and list-initialization (also known as uniform initialization) available:
With this, there is no way it could be interpreted as a function declaration.
As the others said, it is a function declaration. Since C++11 you can use brace initialization if you need to see the empty something that explicitly tells you that a default constructor is used.
The same syntax is used for function declaration - e.g. the function
object
, taking no parameters and returningMyObject
Because the compiler thinks it is a declaration of a function that takes no arguments and returns a MyObject instance.
From n4296 [dcl.init]:
You could also use the more verbose way of construction:
In C++0x this also allows for
auto
: