-2

If I have a following situation:

#include <iostream>

using namespace std;

class A {
public:
    A() {
        cout << "Inside A" << endl;
    }
};

int main() {
    A a();
    return 0;
}

Why is the constructor not invoked?

Pranjal Kaler
  • 483
  • 3
  • 14
  • 1
    [My attempt at value initialization is interpreted as a function declaration, and why doesn't A a(()); solve it?](https://stackoverflow.com/questions/1424510/) is a more appropriate duplicate. [Why “Foo f(Bar());” can be a declaration of a function that takes type Bar and returns type Foo?](https://stackoverflow.com/q/27613904/1968) that you linked to is marked as a duplicate of it. – Remy Lebeau Aug 07 '19 at 19:19
  • @Remy Yes. You’re also right that this isn’t actually an MVP, although it’s so similar that even professionals (exhibit A: yours truly) regularly confuse it. It definitely goes in the same direction as far as expected vs actual behaviour is concerned. – Konrad Rudolph Aug 07 '19 at 19:22
  • @KonradRudolph I almost rode it off as MVP, too. I had to look up MVP before posting my answer, just to make sure. – Remy Lebeau Aug 07 '19 at 19:25

1 Answers1

5

If something looks like a function declaration, the C++ standard requires it be treated as a function declaration.

A a(); does not default-construct an object a of type A. It declares a function a that takes no input parameters and returns an A object as output.

To default-construct a variable a, you need to drop the parenthesis:

A a;

Or, in C++11 and later, you can use curly braces instead of parenthesis:

A a{};

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Maybe you should mention "Most Vexing Parse" somewhere in the answer as well, for future searches as well as giving OP some keywords to research.. – Jesper Juhl Aug 07 '19 at 19:20
  • @JesperJuhl `A a();` is not actually an example of "most vexing parse", which is why I didn't mention it. Though it is commonly confused with "most vexing parse". – Remy Lebeau Aug 07 '19 at 19:22