I asked a question earlier today about singletons, and I'm having some difficulties understanding some errors I encountered. I have the following code:
Timing.h
class Timing {
public:
static Timing *GetInstance();
private:
Timing();
static Timing *_singleInstance;
};
Timing.cpp
#include "Timing.h"
static Timing *Timing::GetInstance() { //the first error
if (!_singleInstance) {
_singleInstance = new Timing(); //the second error
}
return _singleInstance;
}
There are two errors in this code which I can't figure out.
The method
GetInstance()
is declared in the header as static. Why in the cpp file do I have to omit the wordstatic
? It gives the error: "cannot declare member function ‘static Timing* Timing::GetInstance()’ to have static linkage". The correct way to write it is:Timing *Timing::GetInstance() { ... }
Why can't I write
_singleInstance = new Timing();
? It gives the error: "undefined reference to Timing::_singleInstance". I solved this error by defining_singleInstance
as a global var in the cpp file.