I'm new to programing and I was trying for the program which makes the class singleton..Is this the correct approach for making a class singleton??
#include <iostream> using namespace std; class Singleton { private: static bool instanceFlag; static Singleton *single; public: static Singleton* getInstance(); void method(); ~Singleton() { instanceFlag = false; } }; bool Singleton::instanceFlag = false; Singleton* Singleton::single = NULL; Singleton* Singleton::getInstance() { if(! instanceFlag) { single = new Singleton(); instanceFlag = true; return single; } else { return single; } } void Singleton::method() { cout << "Method of the singleton class"; } int main() { Singleton *sc1,*sc2; sc1 = Singleton::getInstance(); sc1->method(); sc2=Singleton::getInstance(); sc2->method(); return 0; } Is this the correct way of making class singleton??
getInstanceinstanceFlagseems pointless, as you already have one of those; the null or non-nullsinglepointer itself (the usefulness of which also being questionable, as a static var in the localgetInstance()member would facilitate most of this).