0

What is the use of declaring constructors in private section in C++? We can declare friend functions and constructors in private section but what is the use?

3 Answers3

0

If you declare the constructor as private, nobody but the class itself can create a new instance of it. Most likely, there is a static method returning a class instance instead. This grants some control about the amount of instances that exist in a given program.

The singleton pattern is one application of this practice. By using a private constructor and some other tricks, you can make sure that only a single instance of this class exists, because the user cannot just create a new instance on his own.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
0

There are many scenarios for having private constructors.

Eg:

  • Restricting object creation
  • For singleton patterns
  • Restricting certain type of constructor (e.g. copy constructor, default constructor)

Private constructor means a user can not directly instantiate a class. Instead, you can create objects, where you have static class functions that can create and return instances of a class.

Another use 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.

Also it is commonly used in the Singleton pattern where the object is accessed through a static member function, Otherwise everyone can create an instance of your class, so it's not a singleton any more. For a singleton by definition there can exist only one instance.

Lokesh
  • 51
  • 1
0

E.g. by making constructor private, you can control the constructions of objects. Maybe you want that only n instances of your object are existing at the same time. You can create a function that counts this. See also Singleton pattern

meddle0106
  • 1,292
  • 1
  • 11
  • 22