Yes it is possible to declare constructors as
private
.
When you declare the constructor as private, you cannot directly instantiate the class from outside. And from only the inside of the class you can create an object of itself. You use
static
functions for this.
Some examples:
1. When you're creating singleton classes (Where only one object of your class exists in your program).
class Foo
{
private:
Foo(){}
public:
static Foo& get_instance()
{
static Foo global_instance;
return global_instance;
}
};
Create
the instance of the above class like this:
Foo& ins = Foo::get_instance();
2. Using static methods to create an instance of a class.
class Foo
{
private:
Foo(){}
public:
static Foo* create_instance()
{
return new Foo();
}
};
Create instances of this class like this:
Foo * ins_a = Foo::create_instance();
Foo * ins_b = Foo::create_instance();