Hi guys, I'm getting " SingletonMain.C:18: undefined reference to `Singleton<MyClass>::instance()' " compiling error.
It doesn't make sense to me because MyClass inherits instance() from Singleton, doesn't it ?
If someone could shed some light on it, I will be grateful.
SingletonMain.C
#include <iostream>
#include "Singleton.h"
using namespace std;
class MyClass : public Singleton<MyClass> {
friend class Singleton<MyClass>;
public:
void setValue(int n) { x = n; }
int getValue() const { return x; }
protected:
MyClass() { x = 0; }
private:
int x;
};
int main() {
MyClass& m = MyClass::instance();
cout << m.getValue() << endl;
m.setValue(1);
cout << m.getValue() << endl;
MyClass& n = MyClass::instance();
cout << n.getValue() << endl;
n.setValue(10);
cout << m.getValue() << endl;
cout << n.getValue() << endl;
}
Singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
template<typename T>
class Singleton {
Singleton(const Singleton&);
protected:
Singleton() {}
virtual ~Singleton() {}
public:
static T& instance();
};
#endif // SINGLETON_H
Singleton.cpp
#include "Singleton.h"
template<typename T>
T& Singleton<T>::instance() {
static T* theInstance = new T;
return *theInstance;
}
Thanks!