Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
3.29/5 (3 votes)
See more:
Hello Everyone,

Is it possible to declare constructor of a class in private scope?

If so, can you please give one small example?

Thanks in advance.


Regards,
Joy
Posted

Yes, it is possible. It is used, for instance, in the Singleton pattern, see this Stack Overflow question [^] for sample code.
 
Share this answer
 
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).
C++
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:
C++
Foo& ins = Foo::get_instance();


2. Using static methods to create an instance of a class.
C++
class Foo
{
private:
   Foo(){}
public:
   static Foo* create_instance()
   {
      return new Foo();
   }
};

Create instances of this class like this:
C++
Foo * ins_a = Foo::create_instance();
Foo * ins_b = Foo::create_instance();
 
Share this answer
 
v5
Yes, you can: it is often used in the Singleton Pattern to give the class and only the class control over when a class instance can be instantiated.
C++
class MyClass
{
private:
  MyClass();
};
Google or Wiki can help you will more complete examples - look for "Singleton Pattern C++" and you will find plenty of examples.
 
Share this answer
 
Comments
chandanadhikari 23-Oct-13 7:14am    
my 5! . I think the basic idea is to put restrictions on the number of ways a client can create objects of a class. Even if you have several overloaded constructors, and you do not want the client to create objects using a couple of them, then put those couple of ctors in private section thereby not allowing clients any access to them.
Yes it is posible only if you do'nt want to create object of that class and you also dont want to make that class abstract. you can make its constructor private so that no one can create its object.

here is sample code

C++
class Shape
{
private Shape();
}
 
Share this answer
 
Comments
Aescleal 25-Oct-13 17:39pm    
While the answer's sort of correctish that code isn't C++ - see Griff's for the real thing.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900