Suppose we have to use a single object of a class throughout the lifetime of an application. In BlackBerry 10, is it possible to declare a global object, which can be used anywhere inside the program?
You could do that, but a better way may be to use a class designed to be a singleton:
Singleton.hpp
class Singleton {
private:
Singleton();
public:
virtual ~Singleton();
static Singleton &instance();
int getMemberField() { return m_memberField; }
void setMemberField(int mf) { m_memberField = mf; }
private:
static Singleton *p_instance;
int m_memberField;
};
Singleton.cpp
Singleton* Singleton::p_instance = NULL;
Singleton::Singleton() {
p_instance = this;
m_memberField = 0;
}
Singleton::~Singleton() {
p_instance = NULL;
}
Singleton& Singleton::instance() {
if (p_instance == NULL) {
p_instance = new Singleton();
}
return *p_instance;
}
In application code
Singleton::instance().setMemberField(25);
Singleton::instance().getMemberField();
The real benifit of this is that the singleton looks after its own global pointer.