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
  • 256,549
  • 94
  • 388
  • 662
R4D4
  • 1,382
  • 2
  • 13
  • 34

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
  • 355,277
  • 75
  • 744
  • 836
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
  • 202,538
  • 53
  • 430
  • 533
  • 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
  • 94,607
  • 11
  • 117
  • 176
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,324
  • 2
  • 27
  • 31