-1

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

class A
{
public:
    A()
    {
        std::cout << "A()\n";
    }
    ~A()
    {
        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 b()?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405

1 Answers1

3

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
songyuanyao
  • 169,198
  • 16
  • 310
  • 405