52

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?

Community
  • 1
  • 1
Atul
  • 1,157
  • 2
  • 16
  • 28
  • 2
    See also http://stackoverflow.com/questions/2062560/what-is-the-use-of-making-constructor-private-in-a-class – StuartLC Jan 10 '11 at 15:58
  • Well spotted, also the accepted answer to this question is useless to C++ --> it's bad taste to create a class of static functions in C++, we're not constrained by "pure" OOP mindset. – Matthieu M. Jan 10 '11 at 17:22
  • http://stackoverflow.com/questions/2062560/what-is-the-use-of-making-constructor-private-in-a-class/16547184#16547184 – Tunvir Rahman Tusher May 23 '13 at 15:12

7 Answers7

69

Private constructor means a user cannot directly instantiate a class. Instead, you can create objects using something like the Named Constructor Idiom, where you have static class functions that can create and return instances of a class.

The Named Constructor Idiom is for more intuitive usage of a class. The example provided at the C++ FAQ is for a class that can be used to represent multiple coordinate systems.

This is pulled directly from the link. It is a class representing points in different coordinate systems, but it can used to represent both Rectangular and Polar coordinate points, so to make it more intuitive for the user, different functions are used to represent what coordinate system the returned Point represents.

 #include <cmath>               // To get std::sin() and std::cos()

 class Point {
 public:
   static Point rectangular(float x, float y);      // Rectangular coord's
   static Point polar(float radius, float angle);   // Polar coordinates
   // These static methods are the so-called "named constructors"
   ...
 private:
   Point(float x, float y);     // Rectangular coordinates
   float x_, y_;
 };

 inline Point::Point(float x, float y)
   : x_(x), y_(y) { }

 inline Point Point::rectangular(float x, float y)
 { return Point(x, y); }

 inline Point Point::polar(float radius, float angle)
 { return Point(radius*std::cos(angle), radius*std::sin(angle)); }

There have been a lot of other responses that also fit the spirit of why private constructors are ever used in C++ (Singleton pattern among them).

Another thing you can do with it is to prevent inheritance of your class, since derived classes won't be able to access your class' constructor. Of course, in this situation, you still need a function that creates instances of the class.

Pang
  • 9,564
  • 146
  • 81
  • 122
wkl
  • 77,184
  • 16
  • 165
  • 176
  • 1
    Not sure, but it'd be good to have copy ctor. Not sure about it tho, because of RVO. – Pawel Zubrycki Jan 10 '11 at 16:00
  • 3
    @Pawel - The C++ FAQ example does not define the copy constructor for `Point` because the class only has primitive members (two `float`), so the compiler's default copy constructor (that does shallow copies) is enough for the example. – wkl Jan 10 '11 at 16:03
  • 1
    +1 Finally, an example that isn't a Singleton or Factory. Named constructors seem much more useful. – chrisaycock Jan 10 '11 at 16:12
  • 2
    I just stumbled upon your sentence "...what coordinate system the returned Point represents". The Point itself uses rectangular coordinates no matter what constructor is used to create the object (otherwise imho this would be a bad example). I checked in the FAQs and I think also there the formulation can be misleading: "...creating Points in either coordinate system:". I think it should better say: "creating Points (with rectangular coordinates) by providing coordinates in either coordinate system as parameters. I may sound picky, but for a newby (like me) such thinks can make the difference – 463035818_is_not_an_ai Jan 16 '15 at 16:24
32

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.

Naveen
  • 74,600
  • 47
  • 176
  • 233
  • 21
    +1. I always get downvoted when I mention a singleton as a case-usage for a particular idiom. Don't want that to happen to you! :) – Moo-Juice Jan 10 '11 at 16:01
6

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.

vrdhn
  • 4,024
  • 3
  • 31
  • 39
5

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

Andrey
  • 59,039
  • 12
  • 119
  • 163
2

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

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.

Simone
  • 11,655
  • 1
  • 30
  • 43
1

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.

smerlin
  • 6,446
  • 3
  • 35
  • 58