Why should we make the constructor private in class? As we always need the constructor to be public.
There are some instances where you might not want to use a public constructor; for example if you want a singleton class.
If you are writing an assembly used by 3rd parties there could be a number of internal classes that you only want created by your assembly and not to be instantiated by users of your assembly.
Some reasons where you may need private constructor:
- The constructor can only be accessed from static factory method inside the class itself. Singleton can also belong to this category.
- A utility class, that only contains static methods.
I saw a question from you addressing the same issue.
Simply if you don't want to allow the others to create instances, then keep the constuctor within a limited scope. The practical application (An example) is the singleton pattern.
You shouldn't make the constructor private. Period. Make it protected, so you can extend the class if you need to.
Edit: I'm standing by that, no matter how many downvotes you throw at this. You're cutting off the potential for future development on the code. If other users or programmers are really determined to extend the class, then they'll just change the constructor to protected in source or bytecode. You will have accomplished nothing besides to make their life a little harder. Include a warning in your constructor's comments, and leave it at that.
If it's a utility class, the simpler, more correct, and more elegant solution is to mark the whole class "static final" to prevent extension. It doesn't do any good to just mark the constructor private; a really determined user may always use reflection to obtain the constructor.
Valid uses:
- One good use of a
protected
constructor is to force use of static factory methods, which allow you to limit instantiation or pool & reuse expensive resources (DB connections, native resources). - Singletons (usually not good practice, but sometimes necessary)
This can be very useful for a constructor that contains common code; private constructors can be called by other constructors, using the 'this(...);' notation. By making the common initialization code in a private (or protected) constructor, you are also making explicitly clear that it is called only during construction, which is not so if it were simply a method:
public class Point {
public Point() {
this(0,0); // call common constructor
}
private Point(int x,int y) {
m_x = x; m_y = y;
}
};
As the others have said, there are a number of patterns that make use of private constructors - such as the Singleton.
The singleton pattern allows only one instance of the class in an application. It does this by having a static private variable within the class of that class's type. A static method instanciates the variable if it is null (using the private constructor), and returns it.
The constructor is private to prevent more than one instance of the class being created.
Such a pattern is useful, for example, when creating a logging class where only one instance should occur to prevent IO conflicts with the log file.
Utility classes could have private constructors. Users of the classes should not be able to instantiate these classes:
public final class UtilityClass {
private UtilityClass() {}
public static utilityMethod1() {
...
}
}
Everyone is stuck on the Singleton thing, wow.
Other things:
- Stop people from creating your class on the stack; make private constructors and only hand back pointers via a factory method.
- Preventing creating copys of the class (private copy constructor)
To leave a "back door" that allows another friend class/function to construct an object in a way forbidden to the user. An example that comes to mind would be a container constructing an iterator (C++):
Iterator Container::begin() { return Iterator(this->beginPtr_); }
// Iterator(pointer_type p) constructor is private,
// and Container is a friend of Iterator.
This ensures that you (the class with private constructor) control how the contructor is called.
An example : A static factory method on the class could return objects as the factory method choses to allocate them (like a singleton factory for example).
By providing a private constructor you prevent class instances from being created in any place other than this very class. There are several use cases for providing such constructor.
A. Your class instances are created in a static
method. The static
method is then declared as public
.
class MyClass()
{
private:
MyClass() { }
public:
static MyClass * CreateInstance() { return new MyClass(); }
};
B. Your class is a singleton. This means, not more than one instance of your class exists in the program.
class MyClass()
{
private:
MyClass() { }
public:
MyClass & Instance()
{
static MyClass * aGlobalInst = new MyClass();
return *aGlobalInst;
}
};
C. (Only applies to the upcoming C++0x standard) You have several constructors. Some of them are declared public
, others private
. For reducing code size, public constructors 'call' private constructors which in turn do all the work. Your public
constructors are thus called delegating constructors:
class MyClass
{
public:
MyClass() : MyClass(2010, 1, 1) { }
private:
MyClass(int theYear, int theMonth, int theDay) { /* do real work */ }
};
D. You want to limit object copying (for example, because of using a shared resource):
class MyClass
{
SharedResource * myResource;
private:
MyClass(const MyClass & theOriginal) { }
};
E. Your class is a utility class. That means, it only contains static
members. In this case, no object instance must ever be created in the program.
One of the important use is in SingleTon class
class Person
{
private Person()
{
//Its private, Hense cannot be Instantiated
}
public static Person GetInstance()
{
//return new instance of Person
// In here I will be able to access private constructor
}
};
Its also suitable, If your class has only static methods. i.e nobody needs to instantiate your class
You may want to prevent a class to be instantiated freely. See the singleton design pattern as an example. In order to guarantee the uniqueness, you can't let anyone create an instance of it :-)
It's really one obvious reason: you want to build an object, but it's not practical to do it (in term of interface) within the constructor.
The Factory
example is quite obvious, let me demonstrate the Named Constructor
idiom.
Say I have a class Complex
which can represent a complex number.
class Complex { public: Complex(double,double); .... };
The question is: does the constructor expects the real and imaginary parts, or does it expects the norm and angle (polar coordinates) ?
I can change the interface to make it easier:
class Complex
{
public:
static Complex Regular(double, double = 0.0f);
static Complex Polar(double, double = 0.0f);
private:
Complex(double, double);
}; // class Complex
This is called the Named Constructor
idiom: the class can only be built from scratch by explicitly stating which constructor we wish to use.
It's a special case of many construction methods. The Design Patterns provide a good number of ways to build object: Builder
, Factory
, Abstract Factory
, ... and a private constructor will ensure that the user is properly constrained.