Hi guys ,i came across coding in a book where they given the below program and named it as singleton class.but here we are able to create 2nd object and also call constructor for second object (only here do we check the status of count and exit from the program after creation of 2nd object).so what if i am right??n what if i can modify this program and make it create only one object??

#include<iostream.h>
class sample
{
    static int count;
    public:
        sample()
        {
            if(count==1)
                exit(0);
                printf("OBJ:%d\n",count);
            count++;
        }
};
int sample::count;
int main()
{
    sample s1;
    sample s2;
    return(0);
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

1. Always use code tag for your snippets (aee this forum rules):
[code=c++] source

[/code]
2. It's a very bad code. Avoid C++ program termination by C library function exit(). It don't call destructors so you can't terminate the program gracely. Probably the only proper method is an exception raising,
3. What's a strange C++/C mixture code with deprecated <iostream.h> and printf...
4. Why return(0) ? Keep it simpler: return 0 . Don't ignore common practice: start you class names from the capital letter (Sample),,,

hi arkm,i would take your suggestion and improve myself and i'm really sorry for posting c++/c mixture code...exact code is like this...

#include<iostream.h>
class Sample
{
static int count;
public:
Sample()
{
if(count==1)
exit(0);
count++;
}
};
int Sample::count;
int main()
{
Sample s1;
Sample s2;
return(0);
}

i do know that it really is a bad code...but i would like to know whether it forms a singleton class or not??

hi jencas ,thanks for your suggestion and i've already google searched it and this was one of the simple as well as bad code i came across .so i would just like to know whether it forms a singleton class or not??

The point of a singletone pattern is not a punishment the program for the second or third class instantiations. You must provide a program with one and only one object of a singleton class. So you present a stub of a singleton class implementation mechanics (one of possible ones) but this "declaration bomb" is not a good singletone class as such (especially with that barbaric exit)...
Look at:
http://sourcemaking.com/design_patterns/singleton/c++/1
http://www.infernodevelopment.com/singleton-c
http://www.codeproject.com/KB/cpp/singletonrvs.aspx
...

This question has already been answered. Start a new discussion instead.