I am trying to create the class that can only allow one object to be created at a time, so i have created private constructor and one public wrapper getInstance() method that will create object for this class, the code goes as follows
#include <iostream>
using namespace std;
class sample
{
static int cnt;
int temp;
private: sample()
{
//temp++;
cnt++;
cout<<"Created "<<++temp<<endl;
}
public:
void show()
{
cout<<"Showing \n";
}
static sample* getInstance()
{
cout<<"count is "<<cnt<<endl;
if(cnt<1)
return (new sample());
else
return NULL;
}
};
int sample::cnt=0;
int main()
{
// cout<<"Hello World";
sample *obj = sample::getInstance();
obj->show();
sample *obj1 = sample::getInstance();
if(obj1 == NULL)
cout<<"Object is NULL\n";
obj1->show();
return 0;
}
How is obj1->show()
is getting called?
OUTPUT :
count is 0
Created 1
Showing
count is 1
Object is NULL
Showing