I am creating a singleton class in C++. Everything is fine except with the object pointers. I cannot instaniate a regular object. But I can define many pointers *aaaa, *bbbb, etc. to the class and access the member functions of the class without using the public Instance() method. Does an pointer to a class an instance in a singleton? Can anybody tell me if this is a good example of singleton?
Here is my code run successfully:
#include "stdafx.h"
#include <iostream>
using namespace std;
class SysParms
{
private:
SysParms(const SysParms&);
int a;
static SysParms * instance; // added by zeng
protected:
SysParms(); //Only a SysParms member can call this
//Prevents a user from creating singleton objects
virtual ~SysParms(); //Prevents just anyone from deleting the singleton
public:
//The "official" access point.
static SysParms* Instance();
int cube (int);
};
//Use anonymous namespace to force internal linkage for instance
// namespace
// {
SysParms* SysParms::instance = 0; //Address of the singleton
// }
SysParms::SysParms()
{
a = 0;
}
int SysParms::cube(int b)
{ return b*b*b;}
SysParms::~SysParms()
{
delete instance;
instance = 0;
}
//The "official" access point
SysParms* SysParms::Instance()
{
//"Lazy" initialization. Singleton not created until it's needed
if (!instance) // if (instance == 0)
{
instance = new SysParms;
}
return instance;
}
int main()
{
SysParms* theSysParmsSingleton;
cout << "Example A: Creating only one instance" << endl;
//
// SysParms obj; //ERROR: singleton objects cannot be created by the user
//
//Use Instance() method to locate singleton.
//Instance() is static as we have no object
theSysParmsSingleton = SysParms::Instance();
cout << "theSysParmsSingleton is located at " << &theSysParmsSingleton
<< endl;
SysParms *aaaa, *bbbb, *cccc, *dddd;
cout << "theSysParmsSingleton is located at " << &aaaa << " " << &dddd
<< endl;
cout << bbbb->Instance()->cube(10) << endl;
cout<< aaaa->cube(6) << endl;
cout << SysParms::Instance()->cube(100) << endl;
return 0;
}