I would not have even bothered creating a private constructor for a utility class.
– PeteshJan 14 '10 at 9:35

15

@Patesh: That's your decision. Other(s) and me would rather prevent an instantiation of utility class than leave out one line private constructor.
– nandaJan 14 '10 at 9:40

I have to agree with this answer, Singleton seems the best fit.
– Jamie KeelingJan 14 '10 at 13:59

9

@dfa: to prevent inheritance, you have to put final on class level. Putting private constructor is pretty much useless for this reason.
– nandaJan 14 '10 at 14:04

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.
– BobMcGeeJan 15 '10 at 16:08

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:

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

Good answer. Why not mention reflection, since this is one avenue for accomplishing something the user cannot?
– BobMcGeeJan 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 CormierJan 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 CormierJan 20 '10 at 2: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.
– evadeflowNov 17 '16 at 16:06

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:

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

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. 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.
– daramarakJan 14 '10 at 9: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.
– BobMcGeeJan 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=).
– Roger PateMar 6 '10 at 5: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.
– AjaxMay 7 '15 at 17:35

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

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.

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.

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.
– daramarakJan 14 '10 at 9:05

@daramarak: thanks, I've no experience with C++. I updated the answer to reflect that this is applicable only in Java
– sateeshJan 14 '10 at 9: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.
– BobMcGeeJan 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.
– sateeshJan 14 '10 at 17:48

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.
– BobMcGeeJan 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.
– gpamparaJan 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.
– nandaJan 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."
– BobMcGeeJan 14 '10 at 15:55

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 SafyanMar 7 '10 at 9: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.
– SysAdminMar 7 '10 at 13:23

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.

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:

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:

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.

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 BarthMar 4 '15 at 5:03

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