Monday, 20 March 2017

c++ - Default constructor with empty brackets



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?


Answer



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:




std::ifstream ifs("file.txt");
std::vector v(std::istream_iterator(ifs), std::istream_iterator());


v is interpreted as a declaration of function with 2 parameters.



The workaround is to add another pair of parentheses:



std::vector v((std::istream_iterator(ifs)), std::istream_iterator());



Or, if you have C++11 and list-initialization (also known as uniform initialization) available:



std::vector v{std::istream_iterator{ifs}, std::istream_iterator{}};


With this, there is no way it could be interpreted as a function declaration.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...