141

Why should we make the constructor private in class? As we always need the constructor to be public.

Massimiliano
  • 16,770
  • 10
  • 69
  • 112
giri
  • 26,773
  • 63
  • 143
  • 176

23 Answers23

136

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.
nanda
  • 24,458
  • 13
  • 71
  • 90
  • 10
    I would not have even bothered creating a private constructor for a utility class. – Anya Shenanigans Jan 14 '10 at 09:35
  • 16
    @Patesh: That's your decision. Other(s) and me would rather prevent an instantiation of utility class than leave out one line private constructor. – nanda Jan 14 '10 at 09:40
  • I have to agree with this answer, Singleton seems the best fit. – Jamie Keeling Jan 14 '10 at 13:59
  • 1
    in some programming languages (notably Java) it also prevents inheritance – dfa Jan 14 '10 at 14:03
  • 9
    @dfa: to prevent inheritance, you have to put `final` on class level. Putting private constructor is pretty much useless for this reason. – nanda Jan 14 '10 at 14:04
  • @narda: right but I never that it is the "best" nor the "usual" way to accomplish non-inheritance. It is just another side-effect :) – dfa Jan 14 '10 at 14:07
  • having *only* private constructors prevents subclassing; if any constructors are protected or public, then its still subclassable. – Will Jan 14 '10 at 17:55
  • 3
    @Will: Not if you use reflection. Declaring constructors private is intended to prevent instantiation (barring reflection), but preventing subclassing is a side effect, not the intent. The appropriate tool for this is declaring the class `final`. This is what Sun did for the String class, and a reasonable chunk of the API that should not be extended. – BobMcGee Jan 15 '10 at 16:08
  • Both cases seem to be anti-patterns nowadays. A colleague was asked in a job interview, how to make a class not instantiable. I guess the answer is, normally you wouldn't need that. – hecko84 May 06 '20 at 12:01
100

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.

Kerido
  • 2,930
  • 2
  • 21
  • 34
  • 3
    In most cases you would want to prevent object copying. So you would not provide an implementation for the private copy constructor. – frast Mar 05 '10 at 11:47
  • from google c++ style guide (another example not on the list but common) --> [if you need to do work in the constructor "consider a factory function \[and making the constructor private\]"](https://google.github.io/styleguide/cppguide.html#Doing_Work_in_Constructors) (text in the square braces is written by me) – Trevor Boyd Smith Jul 05 '16 at 19:40
13

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.
Emile Cormier
  • 28,391
  • 15
  • 94
  • 122
  • Is this different enough, Terry? ;) – Emile Cormier Jan 14 '10 at 08:45
  • Good answer. Why not mention reflection, since this is one avenue for accomplishing something the user cannot? – BobMcGee Jan 14 '10 at 14:05
  • @Bob: You'll have to enlighten me on that one, as I'm mainly a C++ guy and reflection is not really in the C++ vocabulary. ;) – Emile Cormier Jan 14 '10 at 21:56
  • 3
    No one is going to read this, but here goes: I've been downvoted a couple of times on this one. Not upset or anything, but (for the sake of learning) I'd like to know why this is bad? How else could an iterator be constructed with the data it needs to access a container's data? – Emile Cormier Jan 20 '10 at 02:57
  • 2
    @EmileCormier, I think you got unfairly down-voted because people learning C++ are told again and again: "Avoid friend declarations". This advice seems to be aimed at inexperienced C++ programmers who might otherwise use `friend` where it isn't warranted—and there are plenty of cases where it's a bad idea. Sadly, the message has been too well received, and many developers never learn the language well enough to understand that occasional use of `friend` is not only acceptable, but *preferable*. Your example was just such a case. *Deliberate* strong coupling is no crime, it's a design decision. – evadeflow Nov 17 '16 at 16:06
11

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)
Terry Mahaffey
  • 11,775
  • 1
  • 35
  • 44
8

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;
   }
};
Will
  • 73,905
  • 40
  • 169
  • 246
3

We can also have private constructor, to enfore the object's creation by a specific class only(For security reasons).

One way to do it is through having a friend class.

C++ example:

class ClientClass;
class SecureClass 
{
  private:
    SecureClass();   // Constructor is private.
    friend class ClientClass;  // All methods in 
                               //ClientClass have access to private
                               // &   protected methods of SecureClass.
};

class ClientClass
{
public:
    ClientClass();
    SecureClass* CreateSecureClass()
     { 
           return (new SecureClass());  // we can access 
                                        // constructor of 
                                        // SecureClass as 
                                        // ClientClass is friend 
                                        // of SecureClass.
     }
};

Note: Note: Only ClientClass (since it is friend of SecureClass) can call SecureClass's Constructor.

vijayNidumolu
  • 39
  • 1
  • 3
3

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.

Kane
  • 16,471
  • 11
  • 61
  • 86
3

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).

Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
2

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)
BobMcGee
  • 19,824
  • 10
  • 45
  • 57
  • 2
    In my experience there is no absolute truths, even goto might be used if the situation demands it. There are Bad and Evil ways, but as Marshall Cline puts it, sometimes you need to choose between the lesser of evils. http://www.parashift.com/c++-faq-lite/big-picture.html#faq-6.15 As for private constructors, they are necessary and not even bad for you. It just means that no one, including your subclasses should use it. – daramarak Jan 14 '10 at 09:10
  • Gotos have their place, true, but marking a constructor private gains you nothing but troubles down the road. I've edited my post to explain more fully why. – BobMcGee Jan 14 '10 at 13:58
  • It does not *make sense* to copy construct or default construct some classes. In C++ you indicate this by declaring a private ctor without defining it (which is also common for operator=). –  Mar 06 '10 at 05:13
  • Optimizing compilers like Java JIT and GWT actually do make use of private constructors: to limit to scope of instantiation and do a better job inlining / pruning your code. – Ajax May 07 '15 at 17:35
2

when you do not want users to create instances of this class or create class that inherits this class, like the java.lang.math, all the function in this package is static, all the functions can be called without creating an instance of math, so the constructor is announce as static.

shinxg
  • 490
  • 4
  • 9
1

Constructor is private for some purpose like when you need to implement singleton or limit the number of object of a class. For instance in singleton implementation we have to make the constructor private

#include<iostream>
using namespace std;
class singletonClass
{


    static int i;
    static singletonClass* instance;
public:


    static singletonClass* createInstance()
    {


        if(i==0)
        {

            instance =new singletonClass;
            i=1;

        }

        return instance;

    }
    void test()
    {

        cout<<"successfully created instance";
    }
};

int singletonClass::i=0;
singletonClass* singletonClass::instance=NULL;
int main()
{


    singletonClass *temp=singletonClass::createInstance();//////return instance!!!
    temp->test();
}

Again if you want to limit the object creation upto 10 then use the following

#include<iostream>
using namespace std;
class singletonClass
{


    static int i;
    static singletonClass* instance;
public:


    static singletonClass* createInstance()
    {


        if(i<10)
        {

            instance =new singletonClass;
            i++;
            cout<<"created";

        }

        return instance;

    }
};

int singletonClass::i=0;
singletonClass* singletonClass::instance=NULL;
int main()
{


    singletonClass *temp=singletonClass::createInstance();//return an instance
    singletonClass *temp1=singletonClass::createInstance();///return another instance

}

Thanks

Tunvir Rahman Tusher
  • 6,421
  • 2
  • 37
  • 32
1

You can have more than one constructor. C++ provides a default constructor and a default copy constructor if you don't provide one explicitly. Suppose you have a class that can only be constructed using some parameterized constructor. Maybe it initialized variables. If a user then uses this class without that constructor, they can cause no end of problems. A good general rule: If the default implementation is not valid, make both the default and copy constructor private and don't provide an implementation:

class C
{
public:
    C(int x);

private:
    C();
    C(const C &);
};

Use the compiler to prevent users from using the object with the default constructors that are not valid.

Charles
  • 1,084
  • 11
  • 14
  • 2
    When you provide a non default constructor without specifying a default constructor, the default constructor doesn't exist. No need to create it and make it private. – TT_ stands with Russia Feb 04 '14 at 03:29
1

If it's private, then you can't call it ==> you can't instantiate the class. Useful in some cases, like a singleton.

There's a discussion and some more examples here.

Seth
  • 45,033
  • 10
  • 85
  • 120
1

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.

Chathuranga Chandrasekara
  • 20,548
  • 30
  • 97
  • 138
0

Sometimes is useful if you want to control how and when (and how many) instances of an object are created.

Among others, used in patterns:

Singleton pattern
Builder pattern
ssedano
  • 8,322
  • 9
  • 60
  • 98
  • How is a private *constructor* useful in an immutable object? Immutability is about preventing changes to an object *after creation*, while private constructors are about preventing *creation*. – Nils von Barth Mar 04 '15 at 05:03
0

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() {
        ...
    }
}
gpampara
  • 11,989
  • 3
  • 27
  • 26
  • 1
    Why does it matter if the utility class is instantiated? All it does is create an object with no fields and eat a few bytes of memory. – BobMcGee Jan 14 '10 at 14:00
  • Being able to instantiate it creates an ambiguous API. If you design a class as a utility class with no state and want to keep it that way. You could subclass a class with a public constructor. A subclass of some utility methods is idiotic. – gpampara Jan 14 '10 at 14:57
  • @BobMcGee: obviously designing a class that works and designing a class to be used by other people are different things. Those who works in API development (such as Sun people or Google collections guy) will kill anyone trying to say that private constructor in a utility class is useless. – nanda Jan 14 '10 at 15:09
  • @gpampara: Declaring your class final prevents people subclassing. This is what Sun did for the String class. @Nanda: A utility class doesn't *need* a defined constructor. If you don't want it to be extensible, then declare it not to be by using "final." – BobMcGee Jan 14 '10 at 15:55
  • 1
    @BobMcGee: You seems to love to see the example from Sun. Then check this utility class Collections from Sun: http://www.docjar.com/html/api/java/util/Collections.java.html . It's indeed using private constructor. – nanda Jan 15 '10 at 03:57
  • @Nanda: Sun can do it, Google can do it. Their libraries are authoritative: you shouldn't need or want to extend the java.util.Collections library. Anyone else who thinks their own code has the same weight behind it is just arrogant, unless they're using one of a VERY few applications for private constructors. – BobMcGee Jan 15 '10 at 17:31
  • That's my point. It's up to you whether you declare a private constructor in utility classes or not. But those who said that such use case is useless is the one I'm againts to. – nanda Jan 16 '10 at 10:14
  • I have to agree with that. I do it because I explicitly do not want instantiation to be possible - it's personal preference. – gpampara Jan 16 '10 at 12:38
0

Quoting from Effective Java, you can have a class with private constructor to have a utility class that defines constants (as static final fields).

(EDIT: As per the comment this is something which might be applicable only with Java, I'm unaware if this construct is applicable/needed in other OO languages (say C++))

An example as below:

public class Constants {
    private Contants():

    public static final int ADDRESS_UNIT = 32;
    ...
}

EDIT_1: Again, below explanation is applicable in Java : (and referring from the book, Effective Java)

An instantiation of utility class like the one below ,though not harmful, doesn't serve any purpose since they are not designed to be instantiated.

For example, say there is no private Constructor for class Constants. A code chunk like below is valid but doesn't better convey intention of the user of Constants class

unit = (this.length)/new Constants().ADDRESS_UNIT;

in contrast with code like

unit = (this.length)/Constants.ADDRESS_UNIT;

Also I think a private constructor conveys the intention of the designer of the Constants (say) class better.

Java provides a default parameterless public constructor if no constructor is provided, and if your intention is to prevent instantiation then a private constructor is needed.

One cannot mark a top level class static and even a final class can be instantiated.

sateesh
  • 27,947
  • 7
  • 36
  • 45
  • 2
    But in C++ you do not need a class for this. If something doesn't depend on data inside the object, write it as free functions, and free variables. Want encapsulation? Use a namespace. – daramarak Jan 14 '10 at 09:05
  • @daramarak: thanks, I've no experience with C++. I updated the answer to reflect that this is applicable only in Java – sateesh Jan 14 '10 at 09:32
  • 2
    If your object is just encapsulating static variables, why limit instantiation? Why specify anything about the constructor? It won't do any harm if it is instantiated. Seems like you could get similar results declaring the class static and final. – BobMcGee Jan 14 '10 at 14:04
  • @BobMcGee, thanks for your comment. This made me to think (and refer) more about what I have posted. I've edited my answer to add some more reasoning about usefulness of private constructor. – sateesh Jan 14 '10 at 17:48
0

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

SysAdmin
  • 5,455
  • 8
  • 33
  • 34
  • It should be noted that singleton is considered by many to be an "anti-pattern" and a decision to apply it should not be made lightly. A common alternative is dependency injection. – Michael Aaron Safyan Mar 07 '10 at 09:14
  • SingleTon is not an anti-pattern. however, Over use of the pattern (because of Lack of knowledge of its use) is not good. It should be noted that its one of GOF pattern. – SysAdmin Mar 07 '10 at 13:23
0

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 :-)

Seb
  • 2,637
  • 1
  • 17
  • 15
0

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.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
0

In addition to the better-known uses…

To implement the Method Object pattern, which I’d summarize as:

“Private constructor, public static method”
“Object for implementation, function for interface”

If you want to implement a function using an object, and the object is not useful outside of doing a one-off computation (by a method call), then you have a Throwaway Object. You can encapsulate the object creation and method call in a static method, preventing this common anti-pattern:

z = new A(x,y).call();

…replacing it with a (namespaced) function call:

z = A.f(x,y);

The caller never needs to know or care that you’re using an object internally, yielding a cleaner interface, and preventing garbage from the object hanging around or incorrect use of the object.

For example, if you want to break up a computation across methods foo, bar, and zork, for example to share state without having to pass many values in and out of functions, you could implement it as follows:

class A {
  public static Z f(x, y) {
    A a = new A(x, y);
    a.foo();
    a.bar();
    return a.zork();
  }

  private A(X x, Y y) { /* ... */ };
}

This Method Object pattern is given in Smalltalk Best Practice Patterns, Kent Beck, pages 34–37, where it is the last step of a refactoring pattern, ending:

  1. Replace the original method with one that creates an instance of the new class, constructed with the parameters and receiver of the original method, and invokes “compute”.

This differs significantly from the other examples here: the class is instantiable (unlike a utility class), but the instances are private (unlike factory methods, including singletons etc.), and can live on the stack, since they never escape.

This pattern is very useful in bottoms-up OOP, where objects are used to simplify low-level implementation, but are not necessarily exposed externally, and contrasts with the top-down OOP that is often presented and begins with high-level interfaces.

Nils von Barth
  • 3,239
  • 2
  • 26
  • 27
0

On use of private constructors could also be to increase readability/maintainability in the face of domain-driven design. From "Microsoft .NET - Architecing Applications for the Enterprise, 2nd Edition":

var request = new OrderRequest(1234);

Quote, "There are two problems here. First, when looking at the code, one can hardly guess what’s going on. An instance of OrderRequest is being created, but why and using which data? What’s 1234? This leads to the second problem: you are violating the ubiquitous language of the bounded context. The language probably says something like this: a customer can issue an order request and is allowed to specify a purchase ID. If that’s the case, here’s a better way to get a new OrderRequest instance:"

var request = OrderRequest.CreateForCustomer(1234);

where

private OrderRequest() { ... }

public OrderRequest CreateForCustomer (int customerId)
{
    var request = new OrderRequest();
    ...
    return request;
}

I'm not advocating this for every single class, but for the above DDD scenario I think it makes perfect sense to prevent a direct creation of a new object.

Morten Nørgaard
  • 2,609
  • 2
  • 24
  • 24
0

If you create a private constructor you need to create the object inside the class

enter code here#include<iostream>
//factory method
using namespace std;
class Test
{
private:
Test(){
cout<<"Object created"<<endl;
}
public:
static Test* m1(){
    Test *t = new Test();
    return t;
}
void m2(){
    cout<<"m2-Test"<<endl;
  }
};
int main(){
Test *t = Test::m1();
   t->m2();
   return 0;
}