Subject not found.
1.

Can a constructor be private in C++?

Answer»

A constructor is a particular member function of a class that is responsible for initialising the class's objects. When a class object is CREATED in C++, the constructor is automatically invoked. Constructors are typically defined in the public SECTION of a class. So, the question is whether CONSTRUCTION can be defined in the class's private section. The answer to this is a yes. A constructor can be defined in the class's private section.

The ways to use a constructor in the private section of the class:

  • We can use the friend class if we don't want that class to be instantiated by anyone else except a friend class.
  • If we need to create a singleton class, we can utilise the Singleton DESIGN pattern. This SIGNIFIES that the system is driven by a single item or a small number of objects, rather than multiple objects of the same class.
  • Because constructors have the same name as classes, different constructors are distinguished by their argument lists; however, if there are many constructors, an implementation might become error-prone. The Named Constructor Idiom requires you to declare all of the class's constructors in the private or protected sections, and then build public static functions to retrieve the class's objects.


Discussion

No Comment Found