I have always read that private constructor prevent object creation. I have used them in singleton patterns and I know how to create objects while using private constructor(using static methods etc). I know that constructors are used for initialization of objects.
But I don't understand exactly what makes private constructors prevent object creation. What if my object don't gets initialize. I mean it should throw some garbage but why does it restrict ??
I have checked all the existing answers in stackoverflow but I am not getting the exact concept.
To create an object in C++, a constructor needs to be called. If the constructor that needs to be invoked is not accessible, then it can't be called, and the object cannot be created.
The point of a
private
constructor is not preventing object construction. It is about controlling which code can access the constructor, and therefore limiting which code to create an object that is an instance of that class. Aprivate
constructor is accessible to all member functions (static
or otherwise) of the class, and to all declaredfriend
s of the class (which may be individual functions, or other classes) - so any of those can create an instance of the class using aprivate
constructor (assuming the constructor is defined).If the constructor cannot be invoked, the object cannot be initialised. After all, the job of the constructor is to initialise the object. But if the constructor is inaccessible, then the object cannot be constructed, so it is not possible to have an uninitialised object.
Of course, there is nothing preventing the class from having multiple constructors with different access controls (
private
,protected
, andpublic
). Aclass
with apublic
constructor can be constructed, using that constructor, by any code. But any attempt to use aprivate
constructor (by a non-member non-friend
) will still be rejected. So access control allows the (developer of the)class
some measure of control over how an instance is constructed.Not defining (i.e. not implementing) a constructor does prevent construction of an object. If that constructor is
private
, the compiler will reject an attempt to call it (unless the function attempting to create an instance is a member or afriend
, as above). For members and friends of the class, the compiler will permit access to the constructor, but (in a typical compile-then-link toolchain) the linker will not build an executable, since it cannot resolve a call to a function that is not defined. Using the technique of marking a constructorprivate
and not defining it is a common way of preventing code from constructing an instance of the class (by either preventing the code from compiling, or preventing it from running).