What is the use of making constructor private in a

2019-01-02 19:29发布

Why should we make the constructor private in class? As we always need the constructor to be public.

标签: oop
23条回答
无色无味的生活
2楼-- · 2019-01-02 20:20

Sometimes is useful if you want to control how and when (and how many) instances of an object are created.

Among others, used in patterns:

Singleton pattern
Builder pattern
查看更多
春风洒进眼中
3楼-- · 2019-01-02 20:21

Constructor is private for some purpose like when you need to implement singleton or limit the number of object of a class. For instance in singleton implementation we have to make the constructor private

#include<iostream>
using namespace std;
class singletonClass
{


    static int i;
    static singletonClass* instance;
public:


    static singletonClass* createInstance()
    {


        if(i==0)
        {

            instance =new singletonClass;
            i=1;

        }

        return instance;

    }
    void test()
    {

        cout<<"successfully created instance";
    }
};

int singletonClass::i=0;
singletonClass* singletonClass::instance=NULL;
int main()
{


    singletonClass *temp=singletonClass::createInstance();//////return instance!!!
    temp->test();
}

Again if you want to limit the object creation upto 10 then use the following

#include<iostream>
using namespace std;
class singletonClass
{


    static int i;
    static singletonClass* instance;
public:


    static singletonClass* createInstance()
    {


        if(i<10)
        {

            instance =new singletonClass;
            i++;
            cout<<"created";

        }

        return instance;

    }
};

int singletonClass::i=0;
singletonClass* singletonClass::instance=NULL;
int main()
{


    singletonClass *temp=singletonClass::createInstance();//return an instance
    singletonClass *temp1=singletonClass::createInstance();///return another instance

}

Thanks

查看更多
牵手、夕阳
4楼-- · 2019-01-02 20:21

when you do not want users to create instances of this class or create class that inherits this class, like the java.lang.math, all the function in this package is static, all the functions can be called without creating an instance of math, so the constructor is announce as static.

查看更多
明月照影归
5楼-- · 2019-01-02 20:22

One of the important use is in SingleTon class

class Person
{
   private Person()
   {
      //Its private, Hense cannot be Instantiated
   }

   public static Person GetInstance()
   {
       //return new instance of Person
       // In here I will be able to access private constructor
   }
};

Its also suitable, If your class has only static methods. i.e nobody needs to instantiate your class

查看更多
姐姐魅力值爆表
6楼-- · 2019-01-02 20:23

This ensures that you (the class with private constructor) control how the contructor is called.

An example : A static factory method on the class could return objects as the factory method choses to allocate them (like a singleton factory for example).

查看更多
登录 后发表回答