Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   How to create Private Constructor. (http://www.go4expert.com/articles/create-private-constructor-t5489/)

Shishir191 27Jul2007 11:58

How to create Private Constructor.
 
This program shows how to create the private constructor in C++.

Code: Cpp

#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();
}


shabbir 27Jul2007 18:24

Re: How to create Private Constructor.
 
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.

Shishir191 27Jul2007 18:27

Re: How to create Private Constructor.
 
Hi,
Ya you are right. ByMistake i have written that. I appoligies for that. Thanks for you good comment.

asadullah.ansari 29Jan2008 12:03

Re: How to create Private Constructor.
 
Quote:

Originally Posted by shabbir
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.


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.


All times are GMT +5.5. The time now is 08:34.