im making a singleton class in c++ and have a couple of questions. first, heres my .h and .cpp files:
// Singleton.h
class Singleton
{
public:
static Singleton GetSingleton();
void DoSomething();
~Singleton();
private:
Singleton();
static Singleton* _instance;
};
//Singleton.cpp
Singleton* Singleton::_instance = 0;// initialize pointer
//*********************************************************************************************
Singleton::Singleton()
{
std::cout << "Singleton::Singleton" << std::endl;
}
//*********************************************************************************************
Singleton::~Singleton()
{
std::cout << "Singleton::~Singleton" << std::endl;
}
//*********************************************************************************************
Singleton Singleton::GetSingleton()
{
std::cout << "Singleton::GetSingleton" << std::endl;
if(_instance == NULL)
{
_instance = new Singleton();
}
return *_instance;
}
//*********************************************************************************************
void Singleton::DoSomething()
{
std::cout << "Singleton::DoSomething" << std::endl;
}
then in my main.cpp, i simply call:
int _tmain(int argc, _TCHAR* argv[])
{
Singleton::GetSingleton().DoSomething();
return 0;
}
The output is:
Singleton:: GetSingleton
Singleton:: Singleton
Singleton:: DoSomething
Singleton:: ~Singleton
Question 1 - why does the constructor get called ? i never call delete. i would expect the constructor to get called because of the 'new' in ::GetSingleton, but not the destructor.
Question 2 - if i make the destrcutor private, why does the compiler say
Error 2 error C2248: 'Singleton::~Singleton' : cannot access private member declared in class 'Singleton' d:\myWork\paulstest1\main.cpp 12 PaulsTest1
when i am blatently not accessing the destructor anywhere.
thanks in advance.