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

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.


Some reasons where you may need private constructor:

  1. The constructor can only be accessed from static factory method inside the class itself. Singleton can also belong to this category.
  2. A utility class, that only contains static methods.

Tags:

Oop