Key takeaways:
Constructor is a special type of member function that is called when an object of a class is created. It is used to initialize the object's state. However, there are times when we might want to prevent the creation of objects of a class. This is where disabling constructors come into play.
Why disable constructors
Singleton pattern: To ensure that only one instance of a class exists.
Static utility classes: To prevent instantiation of utility classes that only contain static methods.
Immutable classes: To prevent modification of objects after construction, ensuring their state remains constant.
Preventing inheritance: To ensure the class should not be used as a base class for other classes.
Implementation examples
Let's explore the some implementations to disable the constructor:
Example 1: Singleton pattern
This can be useful when we want to ensure that only one instance of a class is created.
Let's take an example of Singleton
a class that has a private constructor. The getInstance
method provides a way to access a single instance of the class. The value
member variable is used to demonstrate that the same instance is being accessed and modified across different parts of the code: