In the code below, why does the compiler not complain for mClass2?
class CMyClass{
private:
CMyClass(){}
};
void TestMethod(){
CMyClass mClass1; //Fails.
CMyClass mClass2(); //Works.
}
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 };
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With