jeudi 21 avril 2016

Singleton Design Pattern - Explicitly stating a Constructor outside the class

I was trying to implement singleton pattern with an assumption of just using a private constructor, private instance of the class and a public static method to return the instance. But I encountered an error to the following code in Visual Studio

// Singleton Invoice
#include <iostream>
using namespace std;

class Singleton {
public:
//Public Static method with return type of Class to access that instance.
static Singleton* getInstance();
private:
//Private Constructor
Singleton();
//Private Static Instance of Class
static Singleton* objSingleton;
};

Singleton* Singleton::objSingleton = NULL;



Singleton* Singleton::getInstance() {
if (objSingleton == NULL) {
//Lazy Instantiation: if the instance is not needed it will never be created
objSingleton = new Singleton();
cout << "Object is created" << endl;
}
else
{
cout << "Object is already created" << endl;
}
return objSingleton;
}

int main() {
Singleton::getInstance();
Singleton::getInstance();
Singleton::getInstance();
return 0;
}

The error as :

LNK2019 unresolved external symbol "private: __thiscall Singleton::Singleton(void)" (??0Singleton@@AAE@XZ) referenced in function "public: static class Singleton * __cdecl Singleton::getInstance(void)" (?getInstance@Singleton@@SAPAV1@XZ)

Then I resolved the error but rewriting the constructor outside the class

Singleton::Singleton() {

}

I would like to know the cause for the error and why a constructor needs to be explicitly written outside the class.

Aucun commentaire:

Enregistrer un commentaire