In the code below, why does the compiler not complain for mClass2?
class CMyClass{
private:
CMyClass(){}
};
void TestMethod(){
CMyClass mClass1; //Fails.
CMyClass mClass2(); //Works.
}
In the code below, why does the compiler not complain for mClass2?
class CMyClass{
private:
CMyClass(){}
};
void TestMethod(){
CMyClass mClass1; //Fails.
CMyClass mClass2(); //Works.
}
Because you've just declared a function mClass2
of zero arguments that returns a CMyClass
. That's a valid option since there could be, say, a static CMyClass
instance which that function has access to. Note that CMyClass
still has a public copy constructor.
(To convince yourself, compile this module to assembler and observe that commenting out the line CMyClass mClass2();
produces the same output.)
Because it is declaring a function and not calling the constructor as you think.
This is called as the Most Vexing Parse in c++.
CMyClass mClass2();
declares a function mClass2()
which takes no parameter and returns CMyClass
People ought to move to the uniform syntax initialization in C++0x/C++11 using the {} brackets instead which removes this issue.
Class C{};