Sérgio Vieira Sérgio Vieira - 6 months ago 37
C++ Question

What's the difference between A a; and A a();?

What is the difference between the declarations of the classes below?

class A
std::cout << "A()\n";
std::cout << "~A()\n";

int main(int argc, char *argv[])
A a; // <-- this call the constructor and destructor
A b(); // <-- this is not!! what is a b()?
return 0;

What is a


This is a most vexing parse issue; a side effect of C++’s rule that anything that can be parsed as a declaration must be interpreted as one. So A b(); is a function declaration, b is a function takes nothing and returns A.

From C++11, you can use braces (list initialization) instead of parentheses; because functions can’t be declared using braces for the parameter list, the "ambiguity" goes away.

A b{}; // calls A's default constructor