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?
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?
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{};