I’ve never run into this before in C++ but it’s odd that it still compiles but doesn’t do what I expected. Can someone tell me what it does do? Please see the code, more info follows.
#include <iostream>
using namespace std;
class Test{
public:
Test();
};
Test::Test(){ cout << "ctor" << endl; }
int main(void){
Test t(); // this compiles but doesn't call the constructor
return(0);
}
It will compile, but if I try to use “t” it won’t. I was only dependent on constructor functionality, and my code didn’t work as expected. The solution is to lose the parenthesis “Test t();” to “Test t;”. My question is what is going on in the “Test t();” example, and what does the compiler think is happening that it lets it compile.
This is the Most Vexing Parse. Basically, according to the C++ parsing rules, what you have there isn’t an object of type
Testnamedt, but rather a function declaration for a functiontwhich takes zero arguments and returns aTest.Incidentally, clang++ actually recognizes this situation and emits a warning, telling you that this probably isn’t doing what you want.