Saturday 25 June 2016

Private Constructor Function and Singleton Pattern

In C++ a constructor can be made private. But what is the use of private constructor ?


Think that you want to create a class in such a way that only one object can be created for this class something called Singleton pattern in C++.
Below is the program to do this.

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. class ABC
  4. {
  5.    public:
  6.    int t;
  7.    static ABC creator()
  8.    {
  9.        static ABC x;
  10.        return x;
  11.     }
  12.     private :
  13.     ABC(){ t=10;}
  14. };
  15. int main()
  16. {
  17.     ABC obj1=ABC::creator();
  18.     cout<<" Value of t= "<<obj1.t;
  19.     //ABC obj2=ABC::creator()           returns same object
  20. }


How it works?


Static function are class variable not object's so static function 'creator()' called using class_name::function_name.
Static object is created inside static function. So private constructor function is called which is a valid call since it is from inside of a member function. So obj1 is created and returned.
Next time when we call static function it does not create new object since object is declare as static so same will be returned.
So only one object is created

No comments:

Post a Comment

THANKS FOR UR GREAT COMMENT

Blogger Widgets