C++ - Singleton Class
If there is a need to create only one instance of a class, then make sure,
1. Default and Copy constructors are declared as private.
2. Assignment operator is declared as private.
3. Have a static function that will return the pointer to the class.
Source Code
#include <iostream>
class MySingletonClass {
private:
int m_nValue;
MySingletonClass() { };
MySingletonClass(const MySingletonClass& other);
const MySingletonClass& operator = (const MySingletonClass& other);
public:
static MySingletonClass* m_pMySingletonClass;
static MySingletonClass* GetInstance()
{
if(m_pMySingletonClass == NULL)
m_pMySingletonClass = new MySingletonClass();
return m_pMySingletonClass;
}
int GetValue() const { return m_nValue; }
void SetValue(int nVal) { m_nValue = nVal; }
};
MySingletonClass* MySingletonClass::m_pMySingletonClass = NULL;
int main()
{
MySingletonClass *p1 = MySingletonClass::GetInstance();
MySingletonClass *p2 = MySingletonClass::GetInstance();
// Both instances will point to the same object
p1->SetValue(100);
std::cout << p2->GetValue();
}
Output
100
|