Re: Singleton base class
Vicky wrote:
Can we define a base class say Singleton whose responsibility will be
make its own derived class Singleton too without tempting the internal
structure and representation of derived class. Ex:
No, because if TestClass has a public constructor & destructor, there is
very little to stop a user from writing
Testclass a;
Testclass b;
and defeating the one-instance policy.
class Singleton
{
};
class TestClass : <access specifier> Singleton
{
// No changes are allowed here because it is already well
defined.
};
We can't even add "friend class Singleton" in TestClass.
If you can live with a runtime error, instead of a compile-time error
for attempting to create multiple instances, you could inherit from this
class:
template <class Derived>
class Singleton
{
public:
static Derived& getInstance()
{
static Derived instance;
return instance;
}
protected:
Singleton()
{
if (m_instanceExist)
throw std::logic_error("Singleton policy broken");
m_instanceExists = true;
}
public:
~Singleton() { m_instanceExists = false; }
private:
Singleton(const Singleton&); // not implemented
void operator=(const Singleton&); // not implemented
static bool m_instanceExists;
};
class TestClass : public Singleton<TestClass>
{
// original contents of TestClass
};
Thanks in advance
Bart v Ingen Schenau
--
a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq
c.l.c FAQ: http://c-faq.com/
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]