#include <iostream>
using namespace std;
class CTest
{
int x;
public:
CTest()
{
x = 3;
cout << "A";
}
};
int main () {
CTest t1;
CTest t2();
return 0;
}
CTest t1 prints “A” of course.
But it seems like nothing happens at t2(), but the code runs well.
So do we use those parentheses without argument? Or why can we use it this way?
This is a quirk of C++ syntax. The line
declares a local variable of type
CTestnamedt1. It implicitly calls the default constructor. On the other hand, the lineIs not a variable declaration, but a local prototype of a function called
t2that takes no arguments and returns aCTest. The reason that the constructor isn’t called fort2is because there’s no object being created here.If you want to declare a local variable of object type and use the default constructor, you should omit the parentheses.
In C++11, you can alternatively say
Which does actually call the default constructor.
Hope this helps!