How to create Private Constructor.

Discussion in 'C++' started by Shishir191, Jul 27, 2007.

  1. Shishir191

    Shishir191 New Member

    Joined:
    Jul 24, 2007
    Messages:
    27
    Likes Received:
    1
    Trophy Points:
    0
    Occupation:
    Software Engineer
    Location:
    Delhi
    This program shows how to create the private constructor in C++.

    Code:
    #include<iostream.h>
    #include<conio.h>
    
    class Test
    {
    	int Data; //Stores the Data
    	
    	Test(int Val):Data(Val)    //Private Constructor
    	{
    	}
    	
    public:
    	
    	static Test Initialize(int Num) //Static Member Function generally called Factory Method.
    	{
    		return Test(Num); //Return the Object.
    	}
    	
    	void Display() //Used to display the result.
    	{
    		cout<<"Value of Data is "<<Data<<endl;
    	}
    };
    
    void main()
    {
    	clrscr();
    	
    	Test Obj = Test::Initialize(10); //Static Member function called to return the object.
    	Obj.Display();
    	
    	getch();
    }
    
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    I have queries for some of your comments.

    Code:
    //Static Member Function generally called Factory Method.
    This is not true. Its for singleton class. Factory method is different. Refer Design pattern in simple examples for singleton as well as factory pattern.
     
  3. Shishir191

    Shishir191 New Member

    Joined:
    Jul 24, 2007
    Messages:
    27
    Likes Received:
    1
    Trophy Points:
    0
    Occupation:
    Software Engineer
    Location:
    Delhi
    Hi,
    Ya you are right. ByMistake i have written that. I appoligies for that. Thanks for you good comment.
     
  4. asadullah.ansari

    asadullah.ansari TechCake

    Joined:
    Jan 9, 2008
    Messages:
    356
    Likes Received:
    14
    Trophy Points:
    0
    Occupation:
    Developer
    Location:
    NOIDA

    It's not needed only in singleton and factory method. Static member can be used any where where you wanna to call static member function without instances of that class.
    Because static member functions are not part of member of that class Actually.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice