Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - What is this doing if the constructor is private?

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

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

void TestMethod(){
    CMyClass mClass1;   //Fails.
    CMyClass mClass2(); //Works.
}
like image 618
R4D4 Avatar asked Jul 21 '11 08:07

R4D4


People also ask

What happens if constructor is private in C++?

A private constructor in C++ can be used for restricting object creation of a constant structure. And you can define a similar constant in the same scope like enum: struct MathConst{ static const uint8 ANG_180 = 180; static const uint8 ANG_90 = 90; private: MathConst(); // Restricting object creation };

Can we use constructor in private?

Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.


1 Answers

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

like image 104
Fred Foo Avatar answered Oct 15 '22 18:10

Fred Foo