What do you think is it possible to declare private constructor e.g.
Yes, it is possible to declare private constructor. Above is completely C++ valid code. But if constructor is private, one can't create an object of such a class and if object can't be created then what is the use of such a class?
Well, it is true that object can't be created but it results in a very interesting design pattern called Singleton design pattern.
in singleton design pattern, class has private constructor and static pointer of itself(ptr). since constructor is private, user can't create object of singleton but can get its pointer via static method(GetPtr). Inside GetPtr function, object of singleton class can be created because private methods can be accessed by other member functions of class.
What is the advantage of singleton class?
It makes sure that there exists only one object of class throughout the program. Only way to access pointer of singleton class is through GetPtr function which internally takes care of it. If object already exists, it returns the same pointer.
singleton design pattern is widely used pattern in software designing. e.g. in GUI based application, it is required to have only one object of front end class that can be accessed throughout the program.
1 2 3 4 | class A { private: A() {cout<<"my constructor"<<endl;} }; |
Yes, it is possible to declare private constructor. Above is completely C++ valid code. But if constructor is private, one can't create an object of such a class and if object can't be created then what is the use of such a class?
Well, it is true that object can't be created but it results in a very interesting design pattern called Singleton design pattern.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class singleton { static singleton *ptr; singleton() { std::cout<<"constructor of class"<<std::endl; } public : static singleton* GetPtr() { if(ptr == NULL) { ptr = new singleton(); } return ptr; } }; singleton* singleton::ptr = NULL; |
in singleton design pattern, class has private constructor and static pointer of itself(ptr). since constructor is private, user can't create object of singleton but can get its pointer via static method(GetPtr). Inside GetPtr function, object of singleton class can be created because private methods can be accessed by other member functions of class.
What is the advantage of singleton class?
It makes sure that there exists only one object of class throughout the program. Only way to access pointer of singleton class is through GetPtr function which internally takes care of it. If object already exists, it returns the same pointer.
singleton design pattern is widely used pattern in software designing. e.g. in GUI based application, it is required to have only one object of front end class that can be accessed throughout the program.