I was practicing how to make a singleton. Everything was going just fine until I decided to play with it. the working version is:
sing.hp:
class GlobalClass
{
private:
GlobalClass(int);
int m_value;
static GlobalClass *s_instance;
// static GlobalClass instance;
public:
int get_value();
void set_value(int v);
static GlobalClass *GetS_instance();
// static GlobalClass GetInstance();
};
sing.cpp
#include"sing.hpp"
#include<iostream>
using namespace std;
GlobalClass * GlobalClass::s_instance = 0;
//GlobalClass GlobalClass::instance;
GlobalClass::GlobalClass(int v = 10)
{
this->m_value = v;
}
int GlobalClass::get_value()
{
return this->m_value;
}
void GlobalClass::set_value(int v)
{
this->m_value = v;
}
GlobalClass * GlobalClass::GetS_instance()
{
if (!s_instance)
{
s_instance = new GlobalClass;
}
return s_instance;
}
//GlobalClass GlobalClass::GetInstance()
//{
//
// return instance;
//}
main.cpp:
#include "sing.hpp"
#include<iostream>
using namespace std;
void foo(void)
{
GlobalClass::GetS_instance()->set_value(1);
cout << "foo: global_ptr is " << GlobalClass::GetS_instance()->get_value() << '\n';
}
int main()
{
cout << "main: global_ptr is " << GlobalClass::GetS_instance()->get_value() << '\n';
foo();
return 1;
}
The above set up works well until I uncomment what I have commented: I get the following error:
~/workspace/singleton2$ g++ *.cpp -o dr
sing.cpp:6:27: error: no matching function for call to ‘GlobalClass::GlobalClass()’
sing.cpp:6:27: note: candidates are:
sing.hpp:5:2: note: GlobalClass::GlobalClass(int)
sing.hpp:5:2: note: candidate expects 1 argument, 0 provided
sing.hpp:2:7: note: GlobalClass::GlobalClass(const GlobalClass&)
sing.hpp:2:7: note: candidate expects 1 argument, 0 provided
Apart from not knowing why this occurred, the strange thing is that: the first line of error message points to line 6 in my program where I have defined the instance, while the error is indicating a mistake in my constructor. could you please help me how to solve this issue? thank you all