15

In the code below, why does the compiler not complain for mClass2?

class CMyClass{
private:
    CMyClass(){}
};

void TestMethod(){
    CMyClass mClass1;   //Fails.
    CMyClass mClass2(); //Works.
}
fredoverflow
  • 246,999
  • 92
  • 370
  • 646
R4D4
  • 1,342
  • 2
  • 13
  • 33

4 Answers4

16

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.)

Fred Foo
  • 342,876
  • 71
  • 713
  • 819
10

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

Community
  • 1
  • 1
Alok Save
  • 196,531
  • 48
  • 417
  • 525
  • 1
    **Most vexing parse** - can't say I've ever heard of that before, I'll have a look at that, thank you. :) – R4D4 Jul 21 '11 at 08:22
1

The second one is a function declaration.

Karoly Horvath
  • 91,854
  • 11
  • 113
  • 173
0

People ought to move to the uniform syntax initialization in C++0x/C++11 using the {} brackets instead which removes this issue.

Class C{};

http://www2.research.att.com/~bs/C++0xFAQ.html#uniform-init

David
  • 3,216
  • 2
  • 25
  • 30