-9

What is the problem?

#include <iostream>
using namespace std;

class Singleton
{
    public:
        void HelloWorld();

        static Singleton* Instance(){
        if (instanza == 0)
            instanza = new Singleton ;
        return instanza;
        }

    protected:
        Singleton();

    private:
        static Singleton* instanza;
};


Singleton* Singleton:: instanza = 0;

void Singleton::HelloWorld()
{
    cout << "Hello World!";
}
int main()
{
    Singleton *p = Singleton ::Instance();
    p->HelloWorld();
    delete p;
}

g++ -Wall -o "singleton" "singleton.cpp" (nella cartella: /home/tarek/Scrivania/Nuovi codici) /tmp/ccL8BxOT.o: nella funzione "Singleton::Instance()": singleton.cpp:(.text._ZN9Singleton8InstanceEv[_ZN9Singleton8InstanceEv]+0x24): riferimento non definito a "Singleton::Singleton()" collect2: error: ld returned 1 exit status Compilazione fallita.

Tarek
  • 1
  • 2
  • 5
    Show us english errors. Just state `LANG=C` in front of the g++ command. – Nidhoegger Sep 01 '16 at 08:36
  • 1
    The message is pretty clear: `Singleton::Singleton()` is not defined. – molbdnilo Sep 01 '16 at 08:39
  • 1
    *What is the problem?* is what you should report. Stackoverflow isn't remote debugging service. And your singleton idiom is broken - what if `Instance` is called before `instanza = 0`? Use local static variables for singletons. – Tomáš Zato Sep 01 '16 at 08:39
  • You forgot to write constructor definition. – Shrikant Sep 01 '16 at 08:40
  • Off topic suggestion: Consider replacing what you have with a Meyers Singleton. It could be as simple as `static YourType& instance() { static YourType s; return s; }`. More complete discussion in the top answer here: http://stackoverflow.com/questions/1008019/c-singleton-design-pattern?noredirect=1&lq=1 – user4581301 Sep 01 '16 at 08:46

2 Answers2

4

Your constructor is just declared not defined.

change it to

...
 protected:
        Singleton() {};//add further implementation here
        //Singleton() = default; for c++11
...

and it should work

Hayt
  • 5,210
  • 30
  • 37
0

You would need define constructor as

Singleton::Singleton() 
{
}
Softec
  • 1,087
  • 11
  • 14