wap to implement singleton class in c++??
Here goes a simple implementation.
#include <iostream>
using namespace std;
class Singleton {
private:
int i;
Singleton() {
cout<<"Constructing"<<endl;
}
static Singleton* instance;
public:
static Singleton* getInstance() {
if (instance == NULL) {
instance = new Singleton();
}
return instance;
}
void set(int j) {
i = j;
}
int get() {
return i;
}
void incr() {
i++;
}
~Singleton() {
cout<<"Destructing"<<endl;
}
};
Singleton* Singleton::instance = NULL;
int main()
{
Singleton *x = Singleton::getInstance();
x->set(5);
x->incr();
Singleton *y = Singleton::getInstance();
cout<<"Result: "<<y->get()<<endl;
}