[c++] private constructor

Possible Duplicate:
What is the use of making constructor private in a class?

Where do we need private constructor? How can we instantiate a class having private constructor?

This question is related to c++ private-constructor

The answer is


It is reasonable to make constructor private if there are other methods that can produce instances. Obvious examples are patterns Singleton (every call return the same instance) and Factory (every call usually create new instance).


It's common when you want to implement a singleton. The class can have a static "factory method" that checks if the class has already been instantiated, and calls the constructor if it hasn't.


For example, you can invoke a private constructor inside a friend class or a friend function.

Singleton pattern usually uses it to make sure that nobody creates more instances of the intended type.


One common use is for template-typedef workaround classes like following:

template <class TObj>
class MyLibrariesSmartPointer
{
  MyLibrariesSmartPointer();
  public:
    typedef smart_ptr<TObj> type;
};

Obviously a public non-implemented constructor would work aswell, but a private construtor raises a compile time error instead of a link time error, if anyone tries to instatiate MyLibrariesSmartPointer<SomeType> instead of MyLibrariesSmartPointer<SomeType>::type, which is desireable.


private constructor are useful when you don't want your class to be instantiated by user. To instantiate such classes, you need to declare a static method, which does the 'new' and returns the pointer.

A class with private ctors can not be put in the STL containers, as they require a copy ctor.


One common use is in the singleton pattern where you want only one instance of the class to exist. In that case, you can provide a static method which does the instantiation of the object. This way the number of objects instantiated of a particular class can be controlled.